javascriptTips3

Must Watch!



MustWatch



find unique items in array

myArray = ['a', 1, 'a', 2, '1']; uniqueItems = [...new Set(myArray)] ['a', 1, 2, '1'] this is the best: ignoreLst.sort(function(a, b){return a-b});

JavaScript User Interface Events

JavaScript Events are defined as the interaction between JavaScript and HTML. Events occur every time the web page is manipulated by the user or the browser. Document Object Model (DOM) version 3 consists of JavaScript events and these are a part of almost all HTML elements and can activate Javascript code. Clicking a button, pressing a key, maximizing a window, etc are all considered as an event. There are various types of JavaScript events however we will specifically discuss JavaScript User Interface Events in this tutorial.

 JavaScript User Interface Events

Events that occur through the user interface are called user interface events and belong to the UiEvent Object. There are various types of events that fall under the category of JavaScript user interface events. The JavaScript user interface events are as follows.
    onabort Event onbeforeunload Event onerror Event onload Event onresize Event onscroll Event onselect Event onunload Event
Each of the above mentioned events are discussed below.

 1.onabort Event

When you abort the loading/downloading of a media i.e. audio/video, the onabort event happens. However, it does not happen due to any error. It does not bubble and neither it is cancelable. It supports the <audio> and <video> HTML tags and is included in DOM level 3. Syntax Syntax of onbabort event is as follows. HTML Syntax <element onabort="funtionName()"> JavaScript Syntax object.onabort = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("abort", script); Example var video = document.getElementById("MyVideo"); video.onabort = function() { alert("Loading aborted");};

 2.onbeforeunload Event

When you are about to unload a document the onbeforeunload event happens. As a result of this event, a confirmation dialog box appears that asks you whether you want to stay on the page or leave it. It does not bubble but it is cancelable. It supports the <body> HTML tag and is included in DOM level 2. Syntax: Syntax of onbeforeunload event is as follows. HTML Syntax: <element onbeforeunload="functionName()"> JavaScript Syntax: object.onbeforeunload = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("beforeunload", script); Example <!DOCTYPE html><html><body onbeforeunload="return myFunction()"><p>Click on the link below</p><a href="https://www.google.com">Click to visit Google</a><script> function myFunction() {return " ";}</script></body></html> In this example, when we click on the link, then before navigation to the google.com, an alert box will appear as demonstrated in the screenshot attached below. Output

 3.onerror Event

If an error occurs when you are loading an external file such as, a document or an image, the onerror event occurs. It does not bubble and neither it is cancelable. It supports <img>, <input type = “image”>, <object>, <link>, and <script> HTML tags and is included in DOM level 2. Syntax: Syntax of onerror event is as follows. HTML Syntax: <element onerror="funtionName()"> JavaScript Syntax: object.onerror = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("error", script); Example <!DOCTYPE html><html><body><img src="catpic.jpg" onerror="myFunction()"><script> function myFunction() { alert('Error! The image could not be loaded');}</script></body></html> Output

 4.onload Event

When you load an object the onload event occurs. The onload event uses the information regarding the user browser to load a suitable version of web pages. It can handle web page cookies, moreover, it does not bubble and can neither be canceled. It supports the <body>, <frame>, <iframe>, <img>, <input type = “image”>, <link>, <script>, and <style> HTML tags and is included in DOM level 2. Syntax: Syntax of onload event is as follows. HTML Syntax: <element onload="functionName()"> JavaScript Syntax: object.onload = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("load", script); Example <!DOCTYPE html><html><body onload="myFunction()"><h1>onload Event</h1><script> function myFunction() { alert("Page was successfully loaded");}</script></body></html> Output After clicking ok the page will load..

 5.onresize Event

When you resize a window the onresize event occurs. It does not bubble and can neither be canceled. It supports the <body> HTML tag and is a part of DOM level 2. Syntax: Syntax of onresize event is as follows. HTML Syntax: <element onresize="funtionName"> JavaScript Syntax: object.onresize = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("resize", script); Example <!DOCTYPE html><html><body onresize="myFunction()"><p>Resize the browser window and it will display the window's height and width</p> <p></p> <script> function myFunction() { var w = window.outerWidth; var h = window.outerHeight; var txt = "Window size: ,demo").innerHTML = txt; } </script> </body> </html> Output Before resizing the window. After resizing

 6.onscroll Event

When you scroll the scrollbar of a web page the onscroll event occurs. It is not cancelable and neither bubbles. It supports <address>, <blockquote>, <body>, <caption>, <center>, <dd>, <dir>, <div>, <dl>, <dt>, <fieldset>, <form>, <h1> to <h6>, <html>, <li>, <menu>, <object>, <ol>, <p>, <pre>, <select>, <tbody>, <textarea>, <tfoot>, <thead>, and <ul> HTML tags and is included in DOM level 2. Syntax: Syntax of onscroll event is as follows. HTML Syntax: <element onscroll="functionName"> JavaScript Syntax: object.onscroll = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("scroll", script); Example <!DOCTYPE html><html><head><style> div { border: 2px solid #bbb; width: 100px; height: 200px; overflow: scroll;}</style></head><body><p>Scroll me</p><div onscroll="myFunction()">HTML is a standard markup language that is used to design the fundamental structure of web pages.<br><br> JavaScript is a scripting language that is used to add dynamic content on the websites.</div><p>Scrolled <span id= "demo"> 0</span> times.</p><script> var scroll = 0; function myFunction() { document.getElementById("demo").innerHTML = scroll += 1;}</script></body></html> In the above code, we simply created a div, gave it some styling, and called the function on the scroll inside a div. Inside the function, add one to the “scroll” variable whenever the function will be invoked. Output Before scrolling. After scrolling.

 7.onselect Event

It occurs when a piece of text is selected in an element. It is not cancelable and neither bubbles. It supports <input type=”file”>, <input type=”password”>, <input type=”text”>, and <textarea> HTML tags and is included in DOM level 2. Syntax: Syntax of onselect event is as follows. HTML Syntax: <element onselect="funtionName()"> JavaScript Syntax: object.onselect = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("select", script); Example <!DOCTYPE html><html><body> Select text: <input type="text" value="Select me" onselect="myFunction()"><script> function myFunction() { alert("Text selected");}</script></body></html> Output Before selecting. After selecting.

 8.onunload Event

When you unload a page or close a browser window the onunload event occurs. This event can also happen when you reload a web page. It does not bubble and neither it is cancelable. It supports the <body> HTML tags and is included in DOM level 2. Syntax: Syntax of onunload event is as follows. HTML Syntax: <element onunload="functionName"> JavaScript Syntax: object.onunload = function(){script}; JavaScript addEventListener() Syntax: object.addEventListener("unload", script); Example <!DOCTYPE html><html><head><script> function myFunction() { alert("onunload event attribute called");}</script></head><body onunload = "myFunction()"><h1>JavaScript onunload Event</h1><h2>This event might not work every time due to difference in browser settings</h2></body></html> Output

 Conclusion

Events that occur through user interface are called user interface events. Events that fall under the category of JavaScript user interface events are onabort event, onbeforeunload event, onerror event, onload event, onresize event, onscrol event, onselect event, and onunload event. All these events are discussed in detail along with appropriate example.

JavaScript Static Class Methods

Static class methods are commonly used for defining the utility functions. Static class methods were embedded in the “ES6” as a JavaScript class-specific method for object-oriented programming (OOP). You can utilize the “static” keyword with the name of the method to create a static class method. Also, static class methods are invoked using the class object, not the class instance. This write-up will discuss the JavaScript static class methods. Moreover, we will also demonstrate examples of static methods definition and their usage in a JavaScript class. So, let’s start!

 Syntax of JavaScript Static Class Methods

To define a static method in your JavaScript class, you must use the “static” keyword with the method name. Check out the below-given syntax for creating a JavaScript static class method: static methodName(){} Here methodName can be anything you would like to name as a method.

 JavaScript Static Class Methods

In JavaScript, static methods are bound to a class but not to the instances of the JavaScript class. That’s why static class methods are used to define utility or helper methods.

 Example 1: Using JavaScript Static Class methods

Use the keyword “static” to define a static method for your JavaScript class. In the below-given example, firstly, we will create an “Employee” having a constructor and a method “getName()”: class Employee { constructor(name) {this.name = name;} getName() {return this.name;}} Within our Employee class, we will define a “showGender()” static method by utilizing the “static” keyword. Our showGender() static class method will return an Employee Object with its “name” property value: static showGender(gender) { let name = gender == "female" ? "Stepheny" : "Stepheny";return new Employee(name);} We will create an “employee” instance that will store the value returned by the showGender() static method. Note that we have invoked the showGender() static method with the “Employee” class object: let employee = Employee.showGender("female"); console.log(employee); Here is the output we get from executing the above-given example: We have already mentioned, you have to invoke the static method with the class object, not with the class instance. For instance, we have created an “employee1” instance of the Employee class. Now, when we invoke our showGender() static method with the “employee1” instance, it will give us an error: let employee1 = new Employee('Jack Smith'); let info = employee1.showGender("male"); As you can see, we cannot access the static method showGender() with the “employee1” instance, which is why we are getting the following error:

 Example 2: Using JavaScript Static Class methods

In this example, firstly, we will create a class named “Bike” and its parameterized constructor, which accepts the bike “name” as its parameter: class Bike { constructor(name) {this.name = name; console.log(name);}} In the next step, we will create a static method “bikeInfo()” which will return a string “This is my bike” whenever we will invoke it: static bikeInfo() {return "This is my bike";} Then, we will create a bike class instance named “myBike” and will pass “Yamaha YZF R15 V3” as an argument to the constructor: let myBike = new Bike("Yamaha YZF R15 V3"); Now, we will call the “bikeInfo()” static method with our class name, which is “Bike”: Bike.bikeInfo(); By invoking the bikeInfo() method of the JavaScript “Bike” class, the program will show the following output: Whereas invoking the static bikeInfo() method with the created Bike class instance will display an error: myBike.bikeInfo(); To utilize the created instance of the Bike class inside the “bikeInfo()” static method, we can pass “myBike” as a parameter to it. Look at the below-given program for the illustration: class Bike { constructor(name) {this.name = name;}static bikeInfo(x) {return "This is my Bike: " + x.name;}} After defining the parameterized static method, we will create a “myBike” instance of the Bike class: let myBike = new Bike("Yamaha YZF R15 V3"); Next, we will invoke the “bikeInfo” static method while passing “myBike” instance as an argument: Bike.bikeInfo(myBike); The output will display “This is my Bike:” string with the bike “name” of our “myBike” instance:

 Conclusion

Using the “static” keyword, you can define the JavaScript static class methods. To invoke the defined static method, you have to create an object of the related class and call the static method with the help of it. JavaScript static methods belong to the class in which they are defined; however, you cannot access them with the class instance. This write-up discussed the JavaScript static class methods. Moreover, we also demonstrated some examples related to static methods definition and their usage in a JavaScript class.

JavaScript Mouse Events

Events operate the interaction between HTML and JavaScript and happen when the web page is manipulated by either the user or the browser, for instance, clicking a button, pressing a key, or resizing a window are all considered events. There is a huge classification of JavaScript events, however, in this write-up, we will explore the category of JavaScript mouse events.

 JavaScript Mouse Events

As suggested by the name JavaScript mouse events are triggered by the interaction of the mouse with the web pages and these events are a part of MouseEvent Object. JavaScript mouse events are
    onclick oncontextmenu ondblclick onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup
This write-up discusses these one-by-one in depth.

 1.onclick Event

When a user clicks on an element the onclick event happens. It bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM level 2. Syntax The syntax of the onclick event is provided below. HTML Syntax <element onclick="funtionName()"> JavaScript Syntax object.onclick = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("click", script); Example <!DOCTYPE html><html><body><p> Click the button below.</p><button onclick="functionName()">Click here</button><p id="tutorial"></p><script> function functionName() { document.getElementById("tutorial").innerHTML = "Onclick Event";}</script></body></html> In the above example, a button will appear on the web page. After clicking the button the onclick event will happen and a message will appear. Output Before the button is clicked. After the button is clicked, the message will appear.

 2.oncontextmenu Event

When the context menu of an element is opened using the right-click, the oncontextmenu event happens. It bubbles and is also cancelable. This event supports all HTML tags and is included in DOM version 3. Syntax The syntax of oncontextmenu event is given below. HTML Syntax <element oncontextmenu="funtionName()"> JavaScript Syntax object.oncontextmenu = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("contextmenu", script); Example <!DOCTYPE html><html><body><p oncontextmenu="functionName()">Right-click on me.</p><script> function functionName() { alert("You just right-clicked!");}</script></body></html> In the above example, when you right click on the text, the oncontextmenu event will trigger and first a dialoag box will appear telling that you just performed a right click and after you click OK on the dialog box the context menu will open. Output When you run the above example the following text will appear. Now when you will right-click the text, the dialog box will appear. After clicking OK, the context menu will open.

 3. ondblclick Event

When an element is double-clicked, the ondblclick event happens. It bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the ondblclick event is provided below. HTML Syntax <element ondblclick="functionName()"> JavaScript Syntax object.ondblclick = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("dblclick", script); Example <!DOCTYPE html><html><body><button ondblclick="functionName()">Double-click me.</button><p id="tutorial"></p><script> function functionName() { document.getElementById("tutorial").innerHTML = "I am learning JavaScript Events.";}</script></body></html> In the above example, a button will appear and when you will double click on the button the ondblclick event triggers and a message will appear. Here is the output. Output Before double clicking the button. After double clicking the button.

 4.onmousedown Event

When you press a mouse button while keeping the mouse over an HTML element, the onmousedown event happens. It bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the onmousedown event is as follows. HTML Syntax <element onmousedown="funtionName()"> JavaScript Syntax object.onmousedown = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mousedown", script); Example <!DOCTYPE html><html><body><button id="jsEvents" onmousedown="mouseDown()"><strong>Click Here</strong></button><script> function mouseDown() { document.getElementById("jsEvents").style.color = "red";}</script></body></html> In the above example, a button will appear on the web page. When you will right click the button while keeping the mouse pointer on the button, the onmousedown event will trigger and the text on the button will change its color from black to red. Output The button before clicking. After right-clicking the mouse while the cursor stays on the button.

 5.onmouseenter Event

When you bring a mouse pointer on an HTML element, the onmouseenter event happens.It cannot bubble and can neither be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the onmouseenter event is as follows. HTML Syntax <element onmouseenter="funtionName()"> JavaScript Syntax object.onmouseenter = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mouseenter", script); Example <!DOCTYPE html><html><body><h1 id="tutorial" onmouseenter="mouseEnter()">Bring the mouse pointer over me.</h1><script> function mouseEnter() { document.getElementById("tutorial").style.color = "red";}</script></body></html> In the above example, a text appear on the web page. When you bring the your mouse cursor over the text, the onmouseenter event will trigger and the color will change to red. Output Before bring the mouse pointer on the text. After bringing the mouse cursor over the text.

 6.onmouseleave Event

When you move your mouse pointer away from an element, the onmouseleave event happens. It cannot bubble and can neither be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the onmouseleave event is as follows. HTML Syntax <element onmouseleave="functionName()"> JavaScript Syntax object.onmouseleave = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mouseleave", script); Example <!DOCTYPE html><html><body><h1 id="tutorial" onmouseleave="mouseLeave()">Bring the mouse pointer over me.</h1><script> function mouseLeave() { document.getElementById("tutorial").style.color = "green";}</script></body></html> In the above example, a text appear on the web page. When you move mouse cursor away from the text, the onmouseenter event will trigger and the color will change to green. Output Before bringing the mouse pointer away from the text. The color will change when mouse pointer moves away.

 7.onmousemove Event

When you move your mouse cursor while keeping it on an element, the onmousemove event happens. The only difference between this event and onmouseenter event is that it bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of onmousemove is given below. HTML Syntax <element onmousemove="functionName()"> JavaScript Syntax object.onmousemove = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mousemove", script); Example <!DOCTYPE html><html><body><h1 id="tutorial">JavaScript Events</h1><p id="demo"></p><script> document.getElementById("tutorial").addEventListener("mousemove", function(event) { funtionName(event);}); function funtionName(event) { alert("This is onmousemove event.")}</script></body></html> In the above example, when you move the mouse cursor over the text the onmousemove event will happen and a dialog box will appear informing you that the onmousemove event has been triggered. Output Before moving the mouse over the text. After.

 8.onmouseout Event

When a mouse cursor leaves an element or any of its children, the onmouseout event happens. The only difference between this and onmouseleave is that it bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the onmouseout event is given below. HTML Syntax <element onmouseout="functionName()"> JavaScript Syntax object.onmouseout = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mouseout", script); Example <!DOCTYPE html><html><body><button id="tutorial" onmouseout="mouseOut()"><h1>Bring mouse here</h1></button><script> function mouseOut() { document.getElementById("tutorial").style.color = "green";}</script></body></html> In the above example, you move the mouse cursor away from the button, the onmouseout event will trigger and the color of the text on the button will change to green. Output Before After

 9.onmouseover Event

When you bring your mouse cursor on an element or any of its children, the onmouseover event happens. It bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of the onmouseover event is provided below. HTML Syntax <element onmouseover="functionName()"> JavaScript Syntax object.onmouseover = function(){script}; JavaScript addEventListener() Syntax object.addEventListener("mouseover", script); Example <!DOCTYPE html><html><body><button id="tutorial" onmouseover="mouseOver()"><h1>Bring mouse here</h1></button><script> function mouseOver() { document.getElementById("tutorial").style.color = "red";}</script></body></html> In the above example, you move the mouse cursor on the button, the onmouseover event will trigger and the color of the text on the button will change to red. Output Before After

 10.onmouseup Event

When a mouse button is released while keeping the pointer on an element the onmouseup event happens. It bubbles and can be canceled. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and is included in DOM version 2. Syntax The syntax of onmouseup event is provided below. HTML Syntax <element onmouseup="functionName()"> JavaScript Syntax object.onmouseup = function(){script};<strong>JavaScript addEventListener() Syntax</strong> object.addEventListener("mouseup", script); Example <!DOCTYPE html><html><body><button id="jsEvents" onmouseup="mouseUp()"><strong>Click Here</strong></button><script> function mouseUp() { document.getElementById("jsEvents").style.color = "green";}</script></body></html> In the above example, a button will appear. When you right click the button and release while keeping the mouse pointer on the button, the onmouse up event will trigger and the color of the text on the button will change to green. Output Before right clicking the button. After releasing the button while keep the mouse pointer on it.

 Conclusion

Events that occur due to mouse movements are referred to as JavaScript mouse events. Events that are classified into the category of JavaScript mouse events are onclick Event, oncontextmenu Event, ondblclick Event, onmousedown Event, onmouseenter Event, onmouseleave Event, onmousemove Event, onmouseout Event, onmouseover Event, and onmouseup Event. All these events are discussed in detail along with appropriate example.

String Iteration Methods

In JavaScript, a string iterator is a method that permits traversing the characters present in a string. By utilizing the JavaScript string iterator, we enable the string added in our code to define their custom iteration behavior. To create a string iterator, you can either use the built-in JavaScript “string @@iterator method” or go for the user-defined string iterator, which can be created with the help of the “Generators”. This write-up will discuss string iteration methods. Moreover, the examples related to the string @@iterator method and JavaScript Generators will be also demonstrated. So, let’s start!

 String @@iterator method

The string iteration method allows you to iterate over the added string in your program. You can make any string iterable by implementing the “@@iterator” method. The string “@@iterator” method returns an iterator object that iterates over all of the code pointed to the added string. The “String[@@iterator]” method is a built-in JavaScript property of a string. By calling the “@@iterator” String property, you can create a string iterator, and in place of “@@iterator,” you have to utilize the “Symbol.iterator” as constant.

 Syntax of string iterator method

var iterator = str[Symbol.iterator](); Here, “iterator” is the name for our string iterator, and the string which needs to be iterated is represented as “str”.

 Using string @@iterator method with next()

In your JavaScript code, you can get your string iterator object using the “next()” method. The “next()” method outputs the keys “Value” and “done,” which comprises a boolean value. The Value key contains the current key value. The done key indicates that if the value is fetched or not, with the “true” and “false” value, where “true” represents that the iteration process is finished and “false” denotes that there exist more values for the iteration. Now, let’s check out some JavaScript examples related to the string @@iterator method.

 Example 1: Using string @@ iterator method without loop

This example will show you how to use the string @@iterator method in your JavaScript program to iterate a specific string. For this purpose, first of all, we will string having ‘MN’ as its value: var str = 'MN'; In the next step, we will create a string iterator for our “str” string: var iterator = str[Symbol.iterator](); If you do not want to use loops for the iteration, you have to invoke the “next()” method according to the length of your string. For instance, we will execute the “iterator.next()” method three times. For the first two times, the “done” value will return false, and when we invoke the specified method a third time, it will return “true” as the iteration is completed and no value is left to iterate: console.log(iterator.next()); // { value: "M", done: false } console.log(iterator.next()); // { value: "N", done: false } console.log(iterator.next()); // { value: undefined, done: true } Have a look at the provided code and its output:

 Example 2: Using string @@ iterator method with for loop

You can also use “loops” to handle the repeated task of string iteration. Want to know how? If yes, then follow the below-given example. Firstly, we will define a string “str” for which we want to create a string “iterator”: const str = 'MNM';const iterator = str[Symbol.iterator](); Next, we will assign the value of the “iterator.next()” function to our “theChar” variable: let theChar = iterator.next(); Then, we will add a simple “for loop,” which will perform the iterator according to the string length property “str.length”. For each iteration of the for loop, the key value and the done value will be displayed to the console window, and the “theChar” will then move to the next string iteration: for(let i = 0; i < str.length ;i++) { console.log(theChar.value , theChar.done); theChar = iterator.next();} Here is the complete look of the provided example along with its output:

 Example 3: Using string @@ iterator method with for..of loop

Using the for..of loop, you can utilize the @@iterator method to iterate over the string data. For each for-of loop iteration, you have to call the “next() method.value” for the iteration purpose. For instance, we have defined a simple string having “MNM” as its value in our JavaScript program: const str = 'MNM'; In the next step, we will create a string iterator for our added “str” string: const iterator = str[Symbol.iterator](); After that, we will assign the iterator value to the “theChar” variable, which will iterate its value using the “next()” method in the for loop: const iterator = str[Symbol.iterator](); Lastly, you can add the “for..of” loop to iterate over the “str” string as follows: //By utilizing the for-of loop console.log("Iterating with for-of loop :") for(let i of str) { console.log(i) } The below-given image shows the output of our JavaScript program:

 Generators

Generators are another helpful feature of JavaScript that permits you to define a function and then use it for creating the string iterator. This procedure is less prone to error and offers an efficient way to create string iterators.

 Syntax of generators

To use the generator in your JavaScript program, you have to follow the below-given syntax: function* () { yield " character1" yield " character2" ....} Here, “*” indicates that we are creating an anonymous function. The keyword “yield” is added to function the execution and returns the iterator object. After doing so, it will again resume its operation.

 Example: Creating user-defined string iterator

In JavaScript, you can also create a user-defined string iterator by utilizing generators. To do so, firstly create a “myIterator” object: var myIterator = {}; Now, define the generator function while specifying the point where the execution will pause with the “yield” keyword. Also, when the generator function is invoked, a “called” string will be shown in our console window: myIterator[Symbol.iterator] = function*(){ console.log("called"); yield "M"; yield "N"; yield "O";};[...myIterator]; After this point, all of the field values will be added to the “myIterator” object: console.log("fields added "); console.log(myIterator); Here is the output which we got from executing the above-given example:

 Conclusion

Using the string @@iterator method and generators, you can easily perform the string iteration process. The string @@iterator method implements the iterator protocol, including the next() method, which returns the characters from collection having two properties value and done. Whereas, Generators let you create a user-defined string iteration method in which you can add the pausing point for the iteration according to your requirements. This write-up discussed string iteration methods. Moreover, the examples related to the string @@iterator method and Generators are also demonstrated.

Object Set Methods

In JavaScript, the “Set” object permits you to store any type of unique values in it, whether they are object references, primitive values such as strings or integers, or complex data types such as Object literals and arrays. A value present in a Set Object can only occur once and is not repeated. Different Object Set methods are offered by JavaScript such as add(), delete(), clear(), and has(). The “add()” object Set method is used for appending values to the set object, delete() and clear() object set methods for deleting a specific or all elements at once, and lastly, the “has()” method is utilized for searching any element in the created Set. This write-up will discuss the object Set methods. Moreover, we will also demonstrate examples related to each object Set methods such as add(), delete(), clear(), and has(). So, let’s start!

 Creating a new Set Object

Before moving towards the object Set methods, the first thing you need to do is to create a new Set object. Using the new Set() constructor, you can easily create a new Set object in your JavaScript program. After creating the Set object, add any data type values you want to store. In the below-given example, we will create a new “setObj1” Set object and then add some numeric values in it such as “2”, “5”, “19”, and “98”: const setObj1 = new Set([2, 5, 19, 98]); console.log(setObj1); After executing the provided code, the console window will show you the type of the created object, which is “Set,” and then the values we have passed to the constructor: You can also create an empty Set object in the following way: const setObj2 = new Set(); console.log(setObj2); The output will declare that “setObj2” is an empty Set object with size “0”: As we have already mentioned, Set comprises unique values. So, when adding repeated values or elements, remember that the Set object will remove the duplicated entries and return the unique set of values. We will create a new Set object: “setObj3” and specify repeated elements values in the constructor. After that, we will call the “console.log()” function to check the elements stored in the setObj3: const setObj3 = new Set([4, 7, 9, 2, 1, 4, 7, 1]); console.log(setObj3); You can see from the output that setObj3 comprises only unique values: At this point, you must be wondering that what if I want to create a Set that will have mixed data types? Yes, you can also store elements having different data types in your Set object. For instance, we want to add a string, some numeric values, and an array as our Set elements. So, we will pass the desired values such as “linuxhint” string with the quotation marks, then “2” and “4” numeric values, and lastly an array “[66,99,100]” enclosed in “[ ]” brackets, all together in the Set constructor: const setObj4 = new Set(["linuxhint", 2, 4, [66, 99, 100]]); console.log(setObj4); After executing the above-given code, a mixed date type Set Object “setObj4” will be created successfully:

 Appending elements to a Set Object

The “add()” method is used for appending a new element or value to the end of a Set object. You have to pass the value which you want to append as an “Argument” in the Set Object “add()” method, and it then appends the specified value to the end of the Set Object. You can append elements to a Set Object either by directly adding the values or through the variable values. We will show you both methods in the below-given example. First of all, we will create a “setObj1” Set object: const setObj1 = new Set(); We have created an empty Set Object; we can now add values directly using the “add()” method. For instance, to add the “It” element to our “setObj1” we will execute the following code, and it will return the setObj1 to the console after appending values: setObj1.add("It"); console.log(setObj1); You can also pass variables as arguments in the “add()” function to append their values in the Set object. For the demonstration, we will create two variables, “b1” and “b2,” and assign the values which we want to append in our “setObj1” Set: const b1 = "is";const b2 = "linuxhint.com"; We will pass both the “b1” and “b2” variables to the setObj1.add() method, and the following code will return the updated Set object: setObj1.add(b1); setObj1.add(b2); console.log(setObj1);

 Deleting a specific Set Object element

The “delete()” method is utilized to delete a specific element that exists in a Set object. For deletion, you must pass the value as an argument in the “setObj1.delete()” method. In the below-given example, we will create a simple “setObj1” Set object and will store some numeric values such as “11”, “22”, “33”, “44”, and “55” in it: const setObj1 = new Set([11, 22, 33, 44, 55]); Now for once, check out the initial elements of the created “setObj1” Set, before deleting a value: console.log("Initial setObj1 elements: "); console.log(setObj1); In the next step, we will delete “22” from the Set elements by using calling the “delete()” method and passing “22” as an argument: setObj1.delete(22); console.log("setObj1 after deleting 22 "); console.log(setObj1); Here is what you are likely to see after executing the provided code:

 Removing All Set Object Elements

This section will show you how to remove all Set object elements at once by utilizing the “clear()” method., the clear() method returns “undefined,” which indicates that all Set object elements are removed successfully. We will help you understand the functionality of the “clear()” method through an example. First of all, we will create a new Set object “setObj1” and store some values in it such as “11”, “22”, “33”, “44”, and “55”: const setObj1 = new Set([11, 22, 33, 44, 55]); Then, we will check out the created Set Object size and its elements: console.log("setObj1 initial size: " + setObj1.size); console.log(setObj1); Now, it’s time to call the “clear()” method and test its working: setObj1.clear(); After executing the clear() method for your set object, all of the elements present in your Set Object will be removed. You can again check the size and look into your Set object: console.log("setObj1 size after clearing elements: " + setObj1.size); console.log(setObj1); The following image comprises the above-given code and the output we got after execution:

 Searching an element in Set Object

JavaScript also offers a “has()” method that can be used to check whether an element exists in a Set object or not. You have to pass the value as an argument while calling the “has()” method with your JavaScript Set object, which will return “true” if the element is found; otherwise, it will display “false”. For instance, we will create a Set object “setObj1” having some string elements “It”, “is”, and “linuxhint.com”: const setObj1 = new Set(["It", "is", "linuxhint.com"]); Then, we will search for the “is” element in our “setObj1()” Set Object by calling the “has()” method and passing “is” as an argument: console.log(setObj1.has("is")); Now, we will search for an element “website” that is not in our Set Object to check out the output: console.log(setObj1.has("website")); As you can see from the output that for searching “is” the program has returned “true”, while for the “website” element, it is showing “false”, which states that “is” is a setObj1 element and “website” is not:

 Conclusion

In JavaScript, add(), delete(), clear(), and has() are the most widely used object Set methods. The add() object Set method is used for appending values to the set object, delete() and clear() object set methods for deleting a specific or all elements at once, and the has() method is utilized for searching any element in the created Set. This write-up discussed the object Set methods. Moreover, we also demonstrated examples related to each object Set methods such as add(), delete(), clear(), and has() method, in this article.

Syntax of JavaScript

The syntax of JavaScript refers to the set of rules that helps to construct a program. In this article, we will describe the basic syntax of JavaScript and will also discuss some basic rules related to the syntax of JavaScrip. Following are some basic rules for the syntax of JavaScript: it is a case sensitive language. every statement ends with a semicolon (;). variables can be started from an alphabetical digit or an underscore (_).

 JavaScript Values

There are two types of values defined: variable Values fixed Values

 Variable Values

Variable values are the variable containers that are used to store the data values., some specific keywords like let, const, and var are used to declare the variables. For example, a variable “x” is defined below: let x; x= 6:

 Types of variables

There are two types of variables: Global variables: Global variables are those which we can access from anywhere in the code. These variables are declared from the outside of the function. Local variables: Local variables are those which are declared inside a function and cannot be accessed from outside of the function. // Global variable declaration var name="Alice"; // Function definition functionnewFunction() { // Local variable declaration var num = 45; // Display the value of Global variable document.writeln(Name);// Display the value of local variable document.writeln("<br>" + num );} // Function call newFunction();

 Fixed Values

Fixed values are known as literals or constant values. There are two types of literals: Numbers: Numbers are the numeric values with or without decimals. The syntax of numbers is given below. 7.228908 Strings: Strings are in text form; this text is written within quotes. The syntax of the string is given below. "Mark Alice"'Mark Alice'

 JavaScript Operators

In JavaScript, arithmetic operators (‘+,’ ‘-,’ ‘*,’ ‘/’) are used to implement some operations on different operands. The assignment operators (=, %=, +=) are also used. One example is given below based on an arithmetic operator: // Declaration of variables var a, b, sum;// Assign value to the variables a= 32; b = 25;// Use arithmetic operator to// add both numbers sum = a + b; document.write(sum);

 Data Types

There are different data types because it holds various types of variables. It is a dynamic programming language; therefore, variable specification is not necessary. JavaScript use two types of data types: Primitive data type:, primitive data is immutable data, which cannot be altered. For example, numbers, strings, boolean numbers, etc. Non-primitive data type: In JavaScript, non-primitive data types are objects and methods such as functions and arrays are non-primitive data types.

 JavaScript Functions

In JavaScript, functions are the code blocks that are used to perform some specific tasks or operations. These functions are reusable and can reduce the computational cost of a program. Syntax of a function is given below: // Definition of function functionfunc() { // Declare a variable var num = 15; // Show the result document.writeln(num); } // Function invoke func();

 JavaScript Keywords

In JavaScript, there are some reserved words with special meanings. Some keywords are given in example: // var keyword is used to define the variable var a, b;// function is the keyword that instruct the browser to create a function function aBc(){};

 JavaScript Comments

Comments are part of the code and are ignored during the execution.. We use comments to add the information and suggestions in the code. They increase the readability of code and make the code user-friendly. In JavaScript, any line between the/*and*/and after double// is considered a comment and not considered during execution. In the given example the syntax of comments is given: let x = 7; // It will be executed// x = 5; It will NOT be executed

 JavaScript Name Identifiers

In JavaScript, identifiers are used to identify the variable names, functions, and keywords. These names must start with: a dollar sign ($) an underscore (_) or any letter from the alphabet. However, numbers at the start of names are not accepted.

 Conclusion

JavaScript is a dynamic programming language, which has some defined rules and syntax. To work with JavaScript we should learn the basic concepts of JavaScript such as data types, keywords, functions, name identifiers, etc. In this tutorial, all basic rules and functions of JavaScripts are defined with proper code examples.

String Concatenation

The basic meaning of concatenation is “to join together” or “to combine”. In different programming, languages concatenation is used to combine different objects or strings. javaScript provides numerous methods to combine two or more strings and return a single string without any gap. For example, if we have a large dataset related to the details of students then it becomes difficult to collect the data of a single student with different features. Therefore, we use a concatenation method to combine the data of a student in a single string like first name, last name, id number, etc. In the following tutorial, we are going to describe the concatenation methods. Three types of concatenation methods are used. Concat() method + operator Template literal Let’s walk through each method and have a better understanding.

 Concat() method

JavaScript provides a built-in concat() method to merge two or more strings.In this method, two or more values from the calling string are merged and returned to a new concatenated string. This function takes two strings and returns a new concatenated string. Syntax string.concat(string0, string1,string2, ..., stringN); All parameters should be in string form, before the implementation of concatenation operation. This method will not change the original input value of strings.

 Example

var sr1 = "Example of "; var sr2 = "Javascript "; var sr3 = "String Concatenation"; var res = sr1.concat(sr2, sr3); console.log(res);//Output: Example of Javascript String Concatenation

 + operator for concatenation

We can also add two strings like we add two numbers by using the “+” operator because + operator is also used for concatenation.

 Example

let str = 'Best '; let str4 = 'Friends'; result = str + str4//Output: Best Friends Not even this, you can also concatenate strings by using shorthand += operator. let str = 'Best'; str += ' '; str += 'Friends';//Output: Best Friends Output

 Template Literal

In JavaScript, template literals are defined with backticks. These literals allow the expressions in the embedded form. In template literal, Interpolation and multi-line and string features can be used. The syntax of the template literal is given below: const pet = 'Cat'; console.log(`i have a ${pet}.`); In the above code, we have binded the variable “pet” inside the template literals. Another example of the template literal for string concatenation is given below, where we are merging three strings using template literals: let str1 = 'String Concatenation'; let str2 = 'Example in'; let str3 = 'JavaScript'; let strJoined = `${str1} ${str2} ${str3}`; console.log(strJoined);//Output: String Concatenation Example THis is how you can concatenate strings using template literals.

 Conclusion

To concatenate strings, javascript provides three different ways, the first is concat() method which takes strings as an argument, the second way is to use “+” operator for combining two or more strings and third is to use template literals for writing long strings along with the variable bindings. In this tutorial, we describe the concatenation methods to merge strings along with examples.

Object Map Methods

A Map is a collection in which each element is stored as a pair of keys and values. The map object is also referred to as an associative array or a dictionary. You can utilize any object or primitive data type as a key or value. Although you can usually access the map object values by their key, however, the Map object preserves the original insertion order. This write-up will discuss object map methods. Moreover, we will also explain the usage of set(), get(), has(), keys(), values(), entries(), delete(), and clear() object map methods with the help of examples. So, let’s start!

 Creating a new map object

First of all, we will add a list of person objects in your JavaScript program: let jack = {name: 'Jack Smith'}, paul = {name: 'Paul Ave '}, max = {name: 'Max William'}; We are going to create a map of persons and their designations. So, the next thing is to create a “designation” map object: let designation = new Map(); The “designation” is an instance of the Map object and has an “object” type: console.log(typeof(designation)); console.log(designation instanceof Map); Now, check out the output of the above-given example:

 Adding elements using set() map method

We will execute the “set()” method to assign the designation to a person. The set() method will map the person “jack” with “editor” post or designation: designation.set(jack, 'editor'); As the set() map method is chainable, we will utilize it to assign multiple designations at once: designation.set(paul, 'admin') .set(max, 'subscriber'); We have successfully input three entries for “jack”, “paul” and “max” with their related designation or post:

 Getting element using get() map method

If you want to check the designation of the “jack”, you can use the get() method: designation.get(jack); The output will display the “jack” Designation, which we have assigned as “editor”: We will now view the designation of “paul” and “max” by executing the following lines of the code: console.log(designation.get(paul)); console.log(designation.get(max)); The output shows that Paul’s designation is “admin” and the designation of Max is “subscriber”:

 Checking existence of a key using has() map method

The “has()” object map method is used for checking if a specific key exists in the map or not. The “has()” method returns a boolean value, where “true” indicates the presence of a key in the map and “false” signifies its absence. To confirm that the “max” key exists, we will invoke the “designation.has()” method while passing “max” as an argument: designation.has(max); If you search for a key that is not present in the designation map object, the has() method will return “false” as its value: designation.has(john);

 Getting number of elements using size map object property

To know about the number of entries, you can utilize your map object’s “size” property. Here, the “size” property will show us the number of entries for our “designation” map object: console.log(designation.size); The output shows that three entries of keys and their respective values are present in our designation map object:

 Iterating over map keys using keys() method

You can use the “keys()” method with a map object to get the key’s values. The keys() map method returns an iterator object, comprising the map object’s key elements. The below-given example will display the person names that exist in the “designation” map object: for (let person of designation.keys()) { console.log(person.name);}

 Iterating over map values using values() method

Similarly, you can execute the “values()” method for getting an iterator object which has the elements values of your map object: for (let post of designation.values()) { console.log(post);}

 Iterating over map elements using entries() method

Another object map method we would like to discuss is “entries()”. The entries() object method also returns an iterator object, containing each map object element’s key value pair: for (let element of designation.entries()) { console.log(`${element[0].name}: ${element[1]}`);}

 Deleting specific map elements using delete() method

To delete a specific entry from your map object, you can invoke the delete() method with the map objects. For instance, we will delete the entry of “jack” from our designation map object by executing the following line of code: designation.delete(jack);

 Deleting all map elements using clear() method

To delete all map elements at once, you can utilize the map object clear() method. For instance, to empty our designation elements, we will invoke the clear() method in the following way: designation.clear(); Now, the size of the designation object will be “0” as no element exists in the created map object:

 Conclusion

The map object is utilized to map keys to values. It saves each map element as a pair of key and its corresponding value. Different object map methods such as set(), get(), has(), keys(), values(), entries(), delete(), and clear() are used for a specific purpose. This write-up discussed object map methods. Moreover, we have also explained the usage of set(), get(), has(), keys(), values(), entries(), delete(), and clear() object map methods, with the help of examples.

JavaScript Nested Functions

JavaScript nested functions are the types of functions defined within another function. One or more functions can be added inside a function, and the scope of the outer functions includes these nested or inner functions. The outer functions are also referred to as the Parent functions, and the inner functions can be named as Child functions nested functions. The variables and parameters of the parent function are accessible to the child function, whereas the parent function cannot access the variables declared inside the child functions. This write-up discussed JavaScript Nested Functions. Moreover, we have also explained the variable scope, Parameters, and return statements of the nested functions with the help of the examples.

 JavaScript Nested Functions

In JavaScript, a nested function is a function that is defined inside or within another function. The procedure for creating a nested function is the same as we follow for the normal function, but to create a nested function, we have to define the new or the child function inside the parent function. Here is the syntax of JavaScript Nested functions: Function parentFunction()//function definition{Function childFunction()//function definition{//body of the child function} childFunction();// child function calling} parentFunction();//parent function calling As you can see from the syntax, we have to define the childFunction() within the parentFunction(). Also, when we want to invoke the childFunction(), we have to call it within the body of the parentFunction().

 Example: Using JavaScript Nested Functions

This example will show you how to create JavaScript nested functions. For this purpose, we will define a parent function named “addNum()”, which has two parameters, “x” and “y”. After doing so, we will create a child function “showMessage()” which prints out a text message to the console window: function addNum(x,y){ //nested function function showMessage(text) { console.log(text); } let sum=x+y; //invoking the nested function showMessage("sum is "+ sum)} Note that we have called the “showMessage()” function inside the function definition of the “addNum()” function. In the next step, we will call the parent function addNum() while passing “5” and “6” as arguments: addNum(5,6) As you can see from the output, we have successfully executed the nested functions of our example:

 Variable scope of JavaScript Nested Functions

Now, let’s talk about the scope of the nested functions. The nested functions have their own scope; however, they can also access the scope of the parent or outer function. You should keep in mind two points about the variable scope of JavaScript nested functions: A nested function is private for its parent function, and a nested function has access to the parent function’s scope. We will explain each of the given statements with the help of examples. As we have stated, the nested function is considered “private” for the function that contains its definition. It means only the parent or the containing function can access the nested function, and you will not be permitted to access it outside of the specified function. This happens because we have defined the inner function inside of the outer function scope. For instance, we have defined an outer function “AddNumber()” in the below-given code and then added the inner function “showMessage()” within the definition of the outer function: function addNumber(x,y){ function showMessage(text) { console.log(text); } let sum=x+y; showMessage("sum is " + sum)} Now, when we try to access the inner function “showMessage()” outside of its scope, it will throw the “Uncaught ReferenceError” error: showMessage('20'); All of the functions, variables, and arguments defined in the outer function are accessible to the created nested function. This ability is known as “Lexical scope”, where the inner function can access the scope of the parent or outer function. We will not pass any arguments to our showMessage() inner function in the below-given example. What we will do is to utilize the arguments “x” and “y” of our “addNumber()” outer function and the “sum” variable: function addNumber(x,y){ function showMessage() { console.log(`sum of %d + %d is %d`,x ,y,sum); } let sum=x+y; showMessage()} Now, we will invoke the outer function “AddNumber()” and pass the “4” and “6” as arguments: addNumber(4,6) Have a look at the below-given output, which signifies that we have successfully accessed the “sum” variable, “x”, and “y” argument of the addNumber outer function in the showMessage() function:

 Returning a JavaScript Nested Function

The outer function has the capability to return the nested function. For instance, in the below-given example, the displayCounter() function have a “count” variable and returns the increment() inner function: function displayCounter() { let count = 0; increment = function () { return ++count; }; return increment;} We will store the displayCounter() function in the “counter” in the next step. Now the concept we need to discuss here is that the “increment()” function will still have access to the “count” property of the “displayCounter()” function when the displayCounter() finished the execution. “Closure”, a JavaScript feature, makes this possible. Here the “count” property is local to the “displayCounter()” function, however, the defined “increment” function can also access it because it is nested inside the “displayCounter()” function: counter = displayCounter() The above-given code will call out the “displayCounter()” function. Then, the displayCounter() function will first initialize the “count” variable to the “0” value and then returns the “increment()” function. Because the “count” property is not destroyed, when we will call the increment function through the “counter()”, each time the “count” property will be incremented according to the added code: console.log(counter()); console.log(counter()); console.log(counter()); Check out the below-given output of the provided example:

 Parameters of JavaScript nested functions

The inner function can also take arguments. For instance, in the following example, the “innerFunction()” is returned by the “outerFunction()” and each of them accepts an argument set: function outerfunction(x) { innerFunction = function (y) { console.log("x %d y %d",x,y) }; return innerFunction;} To get the innerFunction(), we will add the following code in our JavaScript program while passing “3” as an argument for the outerFunction(): InnerFunction=outerfunction(3); Then, we will invoke the innerFunction() with value “7” as an argument: InnerFunction(7); You can also pass the arguments for both outer and inner functions at once: outerfunction(2)(3); Both of the specified lines of the code invoked the innerFunction() and output the passed arguments:

 Conclusion

JavaScript permits you to use nested functions in the program without encountering errors. A child or inner function can be added inside an outer function. All of the local, global variables of the outer function are accessible to the inner function. In the case of the outer function, only global properties values and the methods and variables defined in the parent functions are accessible. This write-up discussed JavaScript Nested Functions. Moreover, we have also explained the variable scope, Closure property, Lexical scope, Parameters, and return statements of the JavaScript nested functions, with the help of the examples.

JavaScript Call() Method

call()” is a predefined JavaScript method that is used for calling methods of various objects. The JavaScript call() method is invoked while taking the object owner as an argument. In this situation, the “this” keyword refers to the object or owner to which the method belongs., all functions are considered object methods, and if that’s not the case, then the function will be utilized as a global object. This write-up will discuss the JavaScript call() method. Moreover, we will also demonstrate how to use the JavaScript call() method for chaining the object constructors and function borrowing with the help of examples. So, let’s start!

 JavaScript call() method

A normal function is considered as an instance of the “Function” type. For instance, we have created a sample display() function that will have some code in its body: function display(){// body of the function} Now, check the association between the display() function and the “Function” by executing the below-given “console.log()” function. It will return “true”, as our defined display() function is an instance of the “Function” type: console.log(show instanceof Function);

 Syntax of the JavaScript call() method

In JavaScript, the “Function” type comprises a method “call()” which has the following syntax: functionName.call(thisArg, arg1, arg2, ...); As you can see in the syntax, the “call()” method will invoke the function “functionName”. The first argument, “thisArg” of the call method, represents “this” value, and it also permits to set the value of “this” to a specified object. The remaining arguments, such as “arg1”, “arg2”… can be the normal arguments of the created function.

 Example 1: Using JavaScript call() method

After defining a function, we have to invoke it to so that it can perform the added operations. In this situation, when the created function is called, the JavaScript function invokes the call() method for that function. For instance, we have created a displayFunc() which will display a string “This is linuxhint.com” on the console window: function displayFunc() { console.log('This is linuxhint.com');} Now, we will invoke our displayFunc() function using the function name: displayFunc(); It will show you the following output: Invoking the displayFunc() function or invoking the call() method for the displayFunc() function will show the same output: displayFunc.call(); Inside a function, “this” value is set to the global object by default, which is “global” on node.js and “window” on web browsers. Executing the below-given function will help you understand this concept: function displayFunc() { console.log(this);} Upon calling the displayFunc(), the value of “this” which is set to the “window” object, will be returned: displayFunc();

 Example 2: Using JavaScript call() method

First of all, we will create a “sum()” function with the parameters “x” and “y”. Inside the body of the “sum()” function, we will add the code to return the addition of the passed arguments: function sum(x, y) {return x + y;} Now, instead of calling the “sum()” function directly, we have utilized the “call()” method for invoking our created “sum()” function. Here, in this case, the value of “this” will be set to the global object: let result = sum.call(this, 89, 98); console.log(result); Have a look at the provided example and its output:

 Example 3: Using the JavaScript call() function

In this example, firstly, we will create a “greeting” variable: var greeting = 'Hello'; Next, we will define a “message” object having a property named “greeting”: var message = { greeting: 'Hi'} After doing so, we will create a “welcome()” function. Inside the “welcome()” function, we will refer to the “greeting” variable with “this” value: function welcome(name){ console.log(this.greeting + ' ' + name);} Now, if we invoke the “welcome()” message while passing “this” and ‘Mark’ as arguments, it will show the below-given output: welcome.call(this,'Mark'); In the other case, you can also invoke the “welcome()” function with the “call()” method while passing the “message” object as the value of “this”: welcome.call(message,'Mark'); Upon doing so, you will see a string “Hi Mark” as output:

 Chaining object constructors using JavaScript call() method

You can also utilize the call() method to chain object constructors. Don’t know how to do that? Check out the following example.

 Example: Chaining object constructors using JavaScript call() method

To show you how to chain object constructors using the “call()” method, firstly, we create an object() function having two parameters length and breadth: function object(length, breadth) { this.length = length; this.breadth = breadth;} Next, we will create another “Widget()” function comprising three parameters: length, breadth, and color. For assigning the value to the “length” and “breadth” variable, we will invoke the object() function with the call() method. For the “color” variable, its value will be assigned within the “Widget()” function: function Widget(length, breadth, color) { object.call(this, length, breadth); this.color = color;} Now, we will create a new “widget” object having a length “90”, breadth “70”, and color as “blue” values: let widget = new Widget(90,70,'blue'); console.log(widget); Check out the output of the above-given example:

 Function borrowing using JavaScript call() method

Function borrowing is a concept in which an object utilizes the method of another object. This section will demonstrate the procedure of function borrowing using the JavaScript call() method.

 Example: Function borrowing using JavaScript call() method

To explain the function borrowing, the first thing we need to do is create two objects and define some functions for each of them. To do so, we will add a “bike” object, having a “name” property and three simple methods: start(), speedup(), and stop(): const bike = { name: 'bike', start: function() { console.log('Start your ' + this.name); }, speedup: function() { console.log('Speed up your ' + this.name) }, stop: function() { console.log('Stop your ' + this.name); }}; After doing so, we will create another object, “aeroplane” which contain a “name” property and a “fly” function: const aeroplane = { name: 'aeroplane', fly: function(){ console.log('Fly your Aeroplane'); }}; Now, we will use the “call()” method for invoking the “start” method of the “bike” object on the “aeroplane” object: bike.start.call(aeroplane); As you can see from the output that we have successfully borrowed the method of the bike object for the aeroplane object:

 Conclusion

In JavaScript, call() is a built-in method that can be used to invoke an object’s method or function as its first parameter. You can also utilize the JavaScript call() method with an object for using a method that belongs to another object. This write-up discussed the JavaScript call() method. Moreover, we have also demonstrated the usage of the JavaScript call() method for chaining the object constructors and function borrowing with the help of examples.

JavaScript Apply() Method

apply() is a predefined JavaScript method that can be used to invoke a function with arguments provided as an array and a given “this” value. The functionality of the JavaScript apply() method and the call() method is the same, except the apply() method passes a single array of arguments rather than individual arguments. You can also utilize the JavaScript apply() method to borrow another object’s method and to append the array elements. This write-up will discuss the JavaScript apply() method. Moreover, we will also demonstrate the usage of the JavaScript apply() method for function borrowing and appending elements of one array to another with the help of examples. So, let’s start!

 JavaScript apply() Method

The JavaScript “apply()” method permits you to invoke a function while passing an “array” as an argument and a given “this” value. To utilize the “Function.prototype.apply()” method, you have to follow its syntax: function.apply(thisArg, [args]); You can see that the JavaScript “apply()” method has two parameters. The first parameter is “thisArg” which denotes the “this” value provided to call the “function”. The next parameter is an array “[args]” which represents the parameters of the “function”. For “args,” an array or array-like object can be passed as an argument. Now, you may be assuming that isn’t JavaScript apply() and call() method are same? The answer is yes. Both methods are similar in functionality; however, instead of individual arguments, the apply() method accepts the function arguments as an array.

 Example: Using JavaScript apply() method

To show you how JavaScript apply() method works, firstly, we will create an “employee” object which will have two properties firstName and the lastName: const employee = { firstName: 'Jack', lastName: 'Smith'} In the next step, we will create a “welcome()” function that accepts two parameters: greeting and message. In the body of the “welcome()” function, we referred to the “employee” object using “this”, which has the firstName and lastName properties: function welcome(greeting, message) { return `${greeting} ${this.firstName} ${this.lastName}. ${message}`;} Now, we will utilize the JavaScript apply() method with the welcome() function by passing the “employee” as an object, ‘Hi’ as a greeting argument, and ‘Hope you are fine’ as a message argument. Here, the arguments of the “welcome()” function are passed as an array to the “apply()” method: let text = welcome.apply(employee, ['Hi', 'Hope you are fine']); console.log(text); Upon executing the above-given example, you will see the following output: In case of using the call() method, you have to pass all the required arguments separately: let text = welcome.call(employee, 'Hi', 'Hope you are fine'); console.log(text);

 Function Borrowing using JavaScript apply() method

You can also use the apply() method to borrow another object’s method without duplicating the code.

 Example: Function Borrowing using JavaScript apply() method

To explain the function borrowing, the first thing we need to do is create two objects and define some function for each of them. For this purpose, we will create our first object named “system”. The “system” object will have two properties: “name” and “active”. Next, we will define two methods, “turnOn()” and “turnOff(),” which will be associated with the “active” property: const system = { name: 'HP Laptop', active: false, turnOn() { this.active = true; return `The ${this.name} is active`; }, turnOff() { this.active = false; return `The ${this.name} is inactive`; }}; After doing so, we will create another object, “client” which contain a “name” and “active” property: const client= { name: 'HP Chromebook', active: false}; Note that we have not added turnOn() and turnOff() methods for the client object. Now, to use the turnOn() method of the “system” object for the “client” object, we can use the “apply()” method for borrowing the specified method: let message = system.turnOn.apply(client); console.log(message); Have a look at the complete code of the provided example and its output:

 Appending an array to another using JavaScript apply() method

The JavaScript apply() method also offers you the facility to append elements of one array to another.

 Example: Appending an array to another using JavaScript apply() method

First of all, we will create two arrays, “array1” and “array2,” having their respective values: let array1 = [10, 20, 30]; let array2 = [70, 80, 90]; We want to append the elements of array2 “70”, “80”, and “90” to array 1. To do so, we will execute the following code: array1.push.apply(array1, array2); console.log(array1); As you can see from the output, we have successfully appended the elements of array2 to array1:

 Conclusion

In JavaScript, apply() is a built-in method that can invoke a function with arguments provided as an array and a given this value. You can also utilize the JavaScript apply() method for using a method that belongs to another object. This write-up discussed the JavaScript apply() method. Moreover, we have also demonstrated the usage of the JavaScript apply() method for function borrowing and appending elements of one array to another with the help of examples.

Invoking a Function as a Method

In JavaScript, functions can be called in a variety of ways. This statement may seem unusual to you if you are a JavaScript beginner, and you may think how a function can be called in multiple ways? Do not we just call it? Well, dear readers, there exist four different ways to call a function, and in this write-up, we will specifically talk about invoking function as a method. Before jumping towards the procedure of invoking function as a method, firstly, let’s show you how to invoke a function as a function. Following this approach, you can easily find the difference between the mentioned function calling practices. So, let’s start!

 Invoking Function as a Function

In JavaScript, most of the functions are invoked or called “as a function”. To show you how to invoke a JavaScript function as a function, we will create a “multiplyFunc()” that will have two parameters, “x” and “y”. In the function body, we will multiply the values stored in the parameters: function multiplyFunc(x, y) { return x * y;} Now to invoke the “mutliplyFunc()” as a function, we will execute the below-given line and pass “2” and “6” as function arguments: multiplyFunc(2, 6); The output of the above-given code is shown below: Because the HTML page is the default global object, the “multiplyFunc()” functionbelongs to the HTML page. The browser window is the page object in a browser. So, the function “multiplyFunc()” will automatically be converted to a window function. The previously given multiplyFunc() function and the window.multipleFunc() will show you the same output: function multiplyFunc(x, y) { return x * y;} window.multiplyFunc(2, 6); As you can see that after calling the window.multiplyFunc() and passing “2” and “6” as arguments, the function has returned “12” as output:

 Invoking Function as Method

In JavaScript, a function must be specified as an object property to invoke it as a method. In such a case, a JavaScript function comprises two parameters: A “function” that belongs to a specific object and a “this” parameter that owns the JavaScript program; however, in this situation, it will store the declared object. In the below-given example, we have created an “employee” object having two properties, “firstName” and “lastName”, and a “FullName” object method. The “FullName” method belongs to the “employee” object and is a function: const employee = { firstName:"Jack", lastName: "Smith", fullName: function () { return this.firstName + " " + this.lastName; }} Now, to invoke the “fullName()” as a method, we will execute the following code: employee.fullName(); The fullName() method will return the firstName and lastName of the “employee” object, which was specified in the function body: Now, we will change the function body to “return this” so that it outputs the owner object: const employee = { firstName:"Jack", lastName: "Smith", fullName: function () { return this; }} Invoke the fullName() function as an “employee” object method in the following way: employee.fullName(); The output will let you know about the employee object properties such as firstName, lastName, and their values. Note that for fullName object property value, “f” is returned, which indicates that fullName is a function:

 Conclusion

By creating a function as an object property, we can invoke a function as a method. When you define a JavaScript function as the property of an object, it comprises two parameters: A function that belongs to a specific object and this parameter that will store the declared object. This write-up discussed invoking function as a method. Moreover, the difference between invoking function as a normal function and invoking function as a method is also demonstrated with the help of examples.

How to Extract String Parts

JavaScript is a scripting language that is mostly used for web development. JavaScript comes bundled with many distinguishing features. Extracting string parts is one of its many noticeable features. Javascript provides two methods to extract string parts that are given below. Each of these methods performs a different type of string extraction.
    substr ( ) method substring ( ) method
Let’s discuss each of these methods in detail.

 substr() Method

For the purpose of extracting a part of the string, the substr() method is used. This method will extract parts of the string from a specified position. As a result, only a specific amount of desired characters will be extracted without altering the original string.

 Syntax of substr() method

The syntax of extracting a part of a string is as follows: string.substr(start, length) In the syntax, the parameter start refers to the position from where you want to extract the string and length refers to the number of characters you want to extract. For better understandability see the following examples.

 Example 1

Suppose. let text= "I want to extract a string part"; Let’s say we want to extract 5 letters from the first index. For doing so, the substr() method arguments would go like this: let result = text.substr(1,5); The extracted string will be stored in the “result” variable. To verify, let’s log the “result” variable on the browser’s console: console.log(result); As you can verify by looking at the output screenshot attached above that we have got our desired substring from the original string.

 Example 2

Now suppose you want to extract a different number of characters from a different position then you simply have to change the parameters. let text= "I want to extract a string part"; Suppose you want to extract 3 characters only this time. The substr ( ) arguments would go like this. let result= text.substr(3,3); For extracting the result we would do this. console.log(result); The screenshot above shows the relevant code along with the output.

 Example 3

In order to extract parts of a string from the end position we use a negative value for the start position. Here is how you do it. let text= "I want to extract a string part";let result= text.substr(-2,5); console.log(result); The output is shown in the following screenshot. Now we will discuss the next string extraction method.

 substring() Method

There is another method for extracting string parts which takes the starting and ending index for extracting part of a string known as substring() method.

 Syntax of substring( ) method

Following is the syntax of the aforementioned method. string.substring(start, end) By determining the syntax of the substring( ) method we can pinpoint the major dissimilarity between the substr( ) and substring( ) methods. The substr ( ) is used to extract a specific number of characters from a specified position while this substring() method is used to extract characters lying between the starting and ending positions of a string. Let us demonstrate a substring( ) method example.

 Example:

Suppose we want to extract the letters from first index to the fifth index. For extracting such a result, the arguments of substring() method would be (1,5) as shown in the javascript code snippet below: let text= "I want to extract a string part"; let result= text.substring(1,5); console.log(result); In the following screenshot the output is demonstrated. A few things that should be kept in mind while using the substring( ) method are as follows:
    Zero and negative values for start and end arguments are considered zero.
    If the value for the start parameter is more than the value of the end parameter then the parameters are swapped. For instance (5,1) will be swapped to (1,5).

 Conclusion

JavaScript provides its users with two easy-to-use methods of extracting parts of a string. First, the substr( ) method allows you to extract a specific number of characters from a particular position in a string, and the substring( ) method is used to extract characters lying in between the start and end indices of a string. In this tutorial, the usage of both of these methods is shown along with appropriate examples.

How to Change the Value of an HTML Element’s Attribute

Web pages are designed using multiple programming languages. Two such web programming languages are HTML and JavaScript. HTML is a web language used to build the basic structure of web pages, meanwhile, JavaScript is used to include dynamic content to the web pages in order to make them captivating. They both have different distinguishing features that make them stand out. One such feature is HTML DOM. HTML DOM which is short for Document Object Model permits JavaScript to change the content of HTML elements. For the purpose of changing the attribute value of an HTML element using JavaScript, HTML DOM provides multiple methods. Using these methods you can alter the attribute value of an HTML element in the following ways:
    Using getAttribute() method Using setAttribute() method
Let’s discuss each of these in detail.

 1.Get Attribute

As the name suggests the getAttribute() method is to extract the current value of the attribute. The syntax of the getAttribute() method is as follows.

 Syntax of getAttribute() method

element.getAttribute (attributename); Lets see example to further understanding.

 Example

Suppose, you want to change src attribute value of <img> element. <img id= "image1" src= "dogpic.jpg"> The above code shows a Nature picture. Now we want to change this dog image to a cat image. We use the following code. <script> document.getElementById("image1").src="snow.jpeg"; </script> The full example with output is shown below. <!DOCTYPE html> <html> <body> <img id= "image1" src= "nature.jpg"> <script> document.getElementById("image1").src="snow.jpg"; </script> <p>The nature image is changed to snow image</p> </body> </html>

 2.Set Attribute

In order to set an attribute on a specific element, we use the setAttribute() method. It updates the value of an attribute existing on an element or sets a new attribute with a new name and value on an element if one does not exist. The syntax of this method is as follows.

 Syntax of setAttribute ( ) method

element.setAttribute(attributename, attributevalue); Let’s see an example to better understand the method.

 Example:

First we create a simple button with a label of “Click here”. <button type="button" id="mybtn">Click here</button> Now we have to select the <button> element and we will do that using its id. var btn = document.getElementById("myBtn"); Now we will use the setAttribute ( ) method to set new attributes. btn.setAttribute("class", "click-btn"); btn.setAttribute("enable", " "); The full code alongwith output is shown below. <!DOCTYPE html><html><body> <button type="button" id="mybtn">Click here</button> <script> var btn = document.getElementById("myBtn"); //This selects an element btn.setAttribute("class", "click-btn"); //This set new attributes btn.setAttribute("enable", " "); //This sets new attributes </script></body></html>

 Conclusion

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute. In this tutorial both of these methods are discussed in detail along with suitable examples.

How to Change HTML Style Through JavaScript

HTML DOM acronym for Document Object Model is a programming interface for documents written in HTML and XML. It provides a logical structure to the documents. HTML DOM defines how HTML documents can be evaluated and changed. Using HTML DOM you can alter the style of HTML elements through JavaScript. The style property of HTML DOM is used for the purpose of changing the style of HTML elements.

 Style Property of HTML DOM

A style attribute of an HTML element is represented by a CSSStyleDeclaration object. In order to return this CSSStyleDeclaration object, the style property is used. This property is used to either get or set the style of elements using various CSS properties.

 Syntax

Syntax of the HTML DOM style property is given as follows. document.getElementById(id).style.property = new style If you simply want to get a style property, use the following syntax. element.style.property However if you want to set a style property, use the given syntax element.style.property= value Now that we have a basic understanding of what HTML DOM style property is. We will now explore some relevant examples.

 Changing HTML style

The given examples demonstrate how we can change style of HTML elements using JavaScript. Example 1Suppose, you want to change the color of <p> element using its id. <!DOCTYPE html><html><body> <p id="para1">HTML DOM Style Property</p> <p id="para2">HTML DOM Style Property</p> <script> document.getElementById("para2").style.color = "red"; </script></body></html> In the above example, we first simply defined two <p> elements and assigned them a unique id. <p id="para1">HTML DOM Style Property</p> <p id="para2">HTML DOM Style Property</p> We then changed the color of <p> element with id=”para2″. In the following piece of code where we’re simply getting our desired element by its id and changing its color to red. <script> document.getElementById("para2").style.color = "red";</script> Here is how it looked before changing the color. After changing the color. Example 2Suppose, you want to change the color as well as the font-family of <h1> element using its id. <!DOCTYPE html><html><body> <h1 id="head1">Learning HTML DOM</h1> <h1 id="head2">Learning HTML DOM</h1> <script> document.getElementById("head2").style.color = "blue"; document.getElementById("head2").style.fontFamily = "Arial"; </script></body></html> In the above example, we first simply defined two <h1> elements and assigned them a unique id. <h1 id="head1">Learning HTML DOM</h1> <h1 id="head2">Learning HTML DOM</h1> We then changed the color and the font family of <h1> element with id=”head2″. In the following piece of code where we’re simply getting our desired element by its id and changing its color to blue and font family to arial. GeSHi Error: GeSHi could not find the language jacascript (using path /home/nginx/domains/linuxhint.com/public/wp-content/plugins/codecolorer/lib/geshi/) (code 2) Here is how it looked before changing the color and the font family. After changing the color and font family it looks like this.

 Conclusion

To alter the style of HTML elements using JavaScript we use the HTML DOM style property. The HTML DOM style property allows you to get or set the style of an HTML element. There can be different approaches to use this property in order to alter the style of HTML elements. This tutorial covers HTML DOM style property and different approaches that can be used to change the style of HTML elements.

Asynchronous Execution

In many programming languages, asynchronous processes are handled by generating a new thread that operates in the background. However,, we have a concept called the execution context and event loop, which prevents the rest of the code from running. When the execution context discovers such code blocks in a program, it sends them back to the event loop for execution before returning them to the call stack. There are three basic types of asynchronous code methods programming: Callbacks, Promises, and async/await keywords. This write-up will discuss Asynchronous Execution. Moreover, we will also demonstrate the JavaScript methods of executing asynchronous execution, such as Callbacks, Promises, async/await, with the help of examples. So, let’s start!

 Callbacks with Asynchronous Execution

Callbacks are one of the most common coding styles to express and handle asynchronous execution. It is a type of function that needs to be called after another function has completed its execution. The callback function is invoked with the response when the specified operation gets completed. Suppose you want to ensure that a particular piece of code in your JavaScript program does not execute until the other finishes its execution. In that case, you can achieve this functionality by utilizing the callback function.

 Example: Callbacks with Asynchronous Execution

Let us give you an example that will assist you with what we have stated. Consider a scenario in which you are required to write a string to a document stream after 7 seconds. In this case, you can use the “setTimeout()” JavaScript built-in function that evaluates an expression or calls any function after a specified amount of time. In our case, we have utilized the “setTimeout()” function to invoke the defined “myFunction()” after 7 seconds: <!DOCTYPE html><html><body><p>Wait for 7 seconds (7000 milliseconds)</p><script> setTimeout(myFunction,7000); function myFunction() { document.write("Asynchronous Execution"); }</script></body></html> You can execute the above-given example in your favorite code editor or any online coding sandbox,; however, we will utilize the JSbin for the demonstration purpose: After executing the provided JavaScript program, you will be asked to wait for “7 seconds”: After 7 seconds, the string “Asynchronous Execution” will be shown as output:

 Promises with Asynchronous Execution

When you chain several function calls together, one of the primary issues of the callbacks is that it becomes difficult to track the flow of the execution. The “.then()” syntax in “Promises” rescues you in such a situation while permitting you to chain promises together. It enables you to link handlers with the added asynchronous value of the success or the cause of the failure. As a result, the asynchronous methods will behave similarly to synchronous ones. Rather than providing the final value immediately, the asynchronous technique returns a promise that offers the value that can be used in further processing. Your Promises object can be in one of the three states: pending, fulfilled, or rejected: Pending: Before an operation occurs, the added Promise is in a pending state. Fulfilled: The fulfilled state of a Promise signifies that the added operation has been completed. Rejected: When an error value is thrown for the incomplete operation, the promise comes under the rejected state.

 Example: Promises with Asynchronous Execution

To show the working of Promises with Asynchronous execution, firstly, we will define a “showMessage()” function which will be invoked for both the success and failure of the added promise: <!DOCTYPE html><html><body><script>function showMessage(text) { document.write(text);} Next, we will create a “myPromise” object, with a function having “myResolve” and “myReject” parameters. We will also add an “if” condition to check the value of the variable “a”, which will then pass the corresponding string to myResolve() or myReject(): let myPromise = new Promise(function(myResolve, myReject) { let a = 5; if (a == 5) { myResolve("Value is Okay"); } else { myReject("Error Encountered"); }}); You can use the “then()” method to utilize the added promise. Our myPromise.then() method will take two arguments: a callback for success and other for the case of failure: myPromise.then( function(value) {showMessage(value);}, function(error) {showMessage(error);});</script></body></html> Execution of the above-given code will show you the following output: Now, on purpose, we will change the value of variable “a” to check if the callback for the failure of the promise is working or not: As you can see, the callback for the failure is displaying “Error Encountered” string according to our JavaScript program coding:

 async/await with Asynchronous Execution

The “async” and “await” keywords are added to the more recent version of JavaScript. These keywords make writing promises easier and permit the user to have complete control over the sequence of promises execution. The async function always returns promises, and the await function is utilized in the async function to halt the execution of the added method while waiting for the promise to resolve. After that, it will resume the function’s execution and output the resolved value.

 Example: async with Asynchronous Execution

Now, in the same example, we will add an async myFunction() which returns a promise: <!DOCTYPE html><html><body><script>function showMessage(text) { document.write(text);} async function myFunction() {return "Hi, this is linuxhint.com";} myFunction().then( function(value) {showMessage(value);}, function(error) {showMessage(error);});</script></body></html> Have a look at the provided code and its output:

 Example: await with Asynchronous Execution

In this example, we will first add the “async” keyword with the showMessage() function definition to output a promise. After doing so, we will specify “await” with the created “myPromise” object so that it will wait for the myPromise: <!DOCTYPE html><html><body><script> async function showMessage() { let myPromise = new Promise(function(resolve, reject) { resolve("Hi, this is linuxhint.com"); }); document.write(await myPromise);} showMessage();</script></body></html> Here is the output we got from executing the above-given example:

 Conclusion

Callbacks, Promises, and async/await keywords are the three methods for handling asynchronous execution. Callbacks enable access to the functions when the asynchronous method has completed the execution; Promises assist in chaining the method together, and the async/await keyword provides additional control over the promises. This write-up discussed Asynchronous Execution. Moreover, we also demonstrated the methods of asynchronous execution such as Callbacks, Promises, async/await with examples.

Class Inheritance

Class Inheritance in JavaScript is a valuable feature that permits code re-usability. By utilizing the class inheritance, the child class will have all access to the properties and methods of the parent class in a JavaScript program. It also allows you to create a child class that inherits the functionality of the parent class while enabling you to override it. This write-up will discuss class inheritance. We will also explain shadowing methods and inheriting static methods using the class inheritance. Moreover, each of the specified sections will be demonstrated with the help of examples. So, let’s start!

 Class Inheritance

The mechanism in which one class inherits another class’s methods and properties is known as Class Inheritance. The “Base” or the “Parent” class is the one whose methods and properties are inherited, whereas the “Derived” or the “Child” class inherits the functionality of the parent class: The “extends” keyword is used to establish the class inheritance between parent and child class, and the “super” keyword is utilized to access the methods and properties of the parent class.

 Example: Class Inheritance

In the below-given example, we will define two classes: Person and Employee, and create the class inheritance between them by utilizing the “super” and “extends” keywords. First of all, we will define a parent or base class named “Person” having a constructor and a showName() method: class Person { constructor(name) { this.name = name; } showName() { console.log('My name is ' + this.name); }} In the next step, we will create the child class named “Employee” which will have a constructor and a “displayStatus()” method. To establish a class inheritance relationship with the “Person” class, you have to use the “extends” keyword and specify the name of the parent class, which is “Person” in our case. After doing so, the “Employee” class will inherit the “Person” class’s methods and properties. Also, in the “Employee” class constructor, we will invoke “super()” to call the constructor of the “Person” class while passing the “name” argument: class Employee extends Person { constructor(name) { super(name); } displayStatus() { console.log('I am an Employee'); }} Now, we will create an “employee” object of the “Employee” class and will pass “Jack” as name arguments in the constructor: let employee = new Employee('Jack'); The created “employee” object inherited all methods and property of the “Person” class. Now, we will invoke the “showName()” method of the “Person” class with it: employee.showName(); Lastly, we will call the “displayStatus()” method of the “Employee” class object: employee.displayStatus(); Have a look at the below-given image of the provided code and its output: As super() initializes the “this” object, you must invoke it first before accessing it. However, if you try to access “this” before executing super(), it will give you an error. For instance, to initialize the “age” property of the “Employee” class in its constructor, we will call the “super()” first and then access the “this” object: class Employee extends Person { constructor(name, age) {super(name);this.age = age;} display() { console.log("I am an Employee");} getAge() {return this.age;}} Now, at the time of creating the “employee1” object of the “Employee” class, we will pass “Jack” as name and “29” as age argument to the constructor: let employee1 = new Employee('Jack', 29); Then, after initialization, we will invoke the “getAge()” method of our Employee class to view the age property value: console.log(employee1.getAge()); Check out the output of the above-given example:

 Shadowing methods using Class Inheritance

Methods having the same name can be defined in both parent and child classes. In such a situation, when you invoke the method of a child class object, it will shadow the method present in the parent class. For instance, the below-given “Student” class is the child class of the “Person” and is redefining the “showName()” method: class Student extends Person { constructor() { super('Jack'); } showName() { console.log('My name is Jack'); }} Now, the “showName()” method exists in the child class and also in the parent class. So, when you call the “showName()” with the “Student” class object, it will invoke the showName() method defined in the child class: let student1 = new Student(); student1.showName(); Here is the example code with its output: If you want to invoke the parent class method having the same name, in the child class, you have to write out “super.methodName(arguments)”. For instance, we will call the “showName()” method of the “Person” (parent) class by adding the line “super.showName()” in our child class showName() method: showName() { super.showName(); console.log('child function'); } Now, when the child class object invokes the “showName()”, it will go through the body of the child class showName() method, then call the parent class showName() method. After completing the execution of the parent class showName() method, the control will be moved back to the showName() method of the child class: let student1 = new Student(); student1.showName(); In the following image, you can see the output of the “showName()” method:

 Inheriting Static Members using Class Inheritance

The child class can also inherit the static methods and properties of the parent class. Let us help you understand this concept by demonstrating an example. In the following example, we will define a static “helloWorld()” method in the same “Person” parent class which will simply output the “Hello World” string upon calling it: class Person{ constructor(name) { this.name = name; } showName() { console.log('My name is ' + this.name); } static helloWorld() { console.log('Hello World'); }} In the next step, we will create “Employee” as a child class of the “Person”, so it can inherit the method and properties of the parent class, including the “helloWorld()” static method: class Employee extends Person { displayStatus() { console.log('I am an Employee'); }} Next, we will invoke the helloWorld() static method through the “Employee” class: Employee.helloWorld(); The Employee.helloWorld() method will be executed same as the Person.helloWorld() method:

 Conclusion:

You can use the extends keyword for creating a class inheritance and the super keyword to refer to the parent class. With the class inheritance mechanism, the child class can access the parent class’s methods and properties. This write-up discussed class inheritance. We have also explained shadowing methods and inheriting static methods using the class inheritance. Moreover, each of the specified sections is demonstrated with the help of examples.

HTML DOM (Document Object Model)

To make an HTML document more dynamic and interactive, JavaScript is required to access the document content and identify the user interacting with it. JavaScript accomplishes this through interacting with the browser with the help of the HTML DOM (Document Object Model), its properties, events, and methods. This write-up will discuss HTML DOM, its significance, and its structure. We will also talk about the properties and methods of the Document Object Model and DOM levels.

 HTML DOM

The HTML Document Object Model or HTML DOM is an XML and HTML programming interface. The Document Object Model creates a logical document structure and defines the method to access and modify them. Because HTML DOM does not identify any object relationships, it is termed as logical structure. HTML DOM is also known for representing web pages in a hierarchical and organized manner so that the users and JavaScript programmers can easily navigate through the document. HTML DOM permits you to access and manipulate HTML elements, classes, tags, attributes, and IDs by utilizing the offered methods and commands.

 Why do you need HTML DOM

JavaScript is utilized to add related functionality if you are using HTML to structure your web pages. When an HTML document gets loaded in the browser, JavaScript can not understand it directly. Therefore, a corresponding Document Object Model is created. The generated DOM represents the same HTML document differently with the help of the objects. After that, JavaScript can readily interpret the HTML DOM. For instance, In an HTML document, JavaScript can not directly understand the tags (<p> paragraph <p>); however, it can understand the object “p” in the Document Object Model. With this capability, JavaScript can use several methods to access the added objects of HTML documents.

 Structure of HTML DOM

HTML DOM or Document Object Model has a tree-like structure, where the tree defines the structure model of the document. In the HTML DOM structure model, “structural isomorphism” is an essential property that states that if you have used two DOM implementations for constructing a representation or model of the same HTML document, they will produce the same structural models be based on the same objects and their relationships.

 Why do we call HTML DOM a Document Model

HTML objects are used for modeling documents. This model comprises the document structure, objects, and their behavior, such as the HTML tag elements having their attributes.

 HTML DOM Properties

Now, let’s check out the document object’s properties that can retrieve and change the document object: Window Object: You will always see the “Window Object” at the top of the DOM hierarchy. Document Object: When you load an HTML document in a browser, it is converted into a document object. Anchor Object: href tags are utilized for representing the Anchor Objects. Form Object: form tags are utilized for representing the Form Objects. Link Object: link tags are utilized for representing the Link Objects. Form Control Elements: Forms can also have other control elements such as Buttons, Reset, radio buttons, Textarea, Checkboxes.

 HTML Document Object Methods

Here is some useful HTML Document object methods which you can use according to your requirements: getElementByClassName(): The getElementByClassName() method is utilized for retrieving elements having the specified class name. getElementByTagName(): The getElementByTagName() method is utilized for retrieving elements with the added tag name. getElementByName(): The getElementByName() method is utilized for retrieving elements having the specified name value. getElementById(): The getElementById() method is utilized for retrieving elements having the specified id value. write(): The write() method is utilized for writing the specified string in the document.

 Example 1: Find and Get HTML element by Id

In the below-given example, we have used the getElementById() method for finding the HTML DOM having the id “p1”: <!DOCTYPE html><html><body><h2>This is linuxhint.com</h2><p id="p1">Find and Get HTML DOM elements by Id</p><p>This is a JavaScript program that utilizes the "getElementsById" method</p><p id="p2"></p><script> const element = document.getElementById("p1"); document.getElementById("p2").innerHTML = "The text of the first paragraph is: " + element.innerHTML;</script></body></html> Execute the above-given program in your favorite code editor or any online coding sandbox; however, we will utilize the JSBin for this purpose: Execution of the above-given JavaScript program will show the following output:

 Example 2: HTML DOM Elements Representation

The following example illustrates the representation of HTML elements in DOM (Document Object Model): <table> <ROWS> <tr> <td>Bike</td> <td>Airplane</td> </tr> <tr> <td>Truck</td> <td>Bus</td> </tr> </ROWS> </table> Here is the representation of the above-given elements in a tree-like structure:

 HTML DOM Level

HTML DOM consists of four levels: Level 0, Level 1, Level 2, and Level 3.

 DOM Level 0

This level offers a low-level interface set.

 DOM Level 1

DOM Level 1 comprises HTML and CORE parts. HTML supplies high-level interfaces that can be utilized to represent HTML documents and the CORE part is used to represent the structured document.

 DOM level 2

DOM level 2 is based on six specifications: RANGE, TRAVERSAL, STYLE, EVENTS, AND CORE2. RANGE: It permits HTML programs for dynamically allocating a content range in the document. TRAVERSAL: It permits HTML programs to traverse the document dynamically. STYLE: It permits programs to retrieve and set the style sheets’ content. EVENTS: When a user interacts with a web page, EVENTS are the scripts executed as a result of it. VIEWS: It permits HTML programs to retrieve and set the document’s content.

 DOM Level 3

DOM level 3 is based on five specifications: XPATH, EVENTS, VALIDATION, SAVE, LOAD, and CORE3. XPATH: It is a path language utilized for accessing the tree structure of DOM. EVENTS: It enhances the functionality of DOM Level 2 Events. VALIDATION: It permits the HTML program to modify the structure and document’s content while ensuring that the provided document is valid. SAVE and LOAD: The HTML program permits dynamically loading and saving the XML document content into a DOM document. CORE3: It enhances the functionality of DOM Level 2 Core.

 Conclusion

HTML DOM or the Document Object Model is crucial for developing interactive websites. It is a user interface that lets a programming language change the website’s style, structure, and content. HTML DOM also acts as an interface between HTML and JavaScript. This write-up discussed HTML DOM, its significance, and its structure. We have also talked about the properties and methods of Document Object Model and DOM levels.

How to Iterate through Objects

Knowing how to iterate through an enumerable dataset is essential for JavaScript beginners. The data you need to iterate can be in any form, such as maps, lists, arrays, and objects. Different JavaScript methods are utilized for iterating through objects and fetching the multiple key-value pairs. Major four of them are for..in loop, Object.keys() method, Object.values() method, and Object.entries() method. This write-up will discuss the methods for iterating through objects. Moreover, the procedures related to object iteration such as for..in loop, Object.keys() method, Object.values() method, and Object.entries() method, will be also demonstrated with examples. So, let’s start!

 Iterate through Objects by utilizing for..in loop

One of the most common methods to iterate through the object properties is using the “for..in” loop. The code you will add inside the for..in loop will be executed once for each property of your object.

 Example: Iterating through Objects by utilizing for..in loop

First, you have to create an object in a JavaScript program. For instance, in the below-given example, we have created a “user” object having “name”, “age”, “email”, and “active” as its properties: const user = { name: 'Jack Smith', age: 28, email: 'jackSmith232@gmail.com', active: true }; Next, we will use the “for..in” loop to iterate through the created user object. The “for..in” loop will return the object properties or keys and their values: // iterate through the user objectfor (const key in user){ console.log(`${key}: ${user[key]}`);} Here is the complete code of the provided example with its output:

 Iterate through Objects by utilizing Object.keys() method

To make iterating through objects easier, the Object.keys() method was added to ES6. You have to pass the object you want to iterate, and the JavaScript Object.keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

 Example: Iterating through Objects by utilizing Object.keys() method

For the demonstration purpose, we will create a “courses” object having different courses as its properties such as “db”, “javascript”, “cp”, and “dld” and will assign each of some them specific values: const courses = { db: 45, javascript: 67, cp: 23, dld: 15 }; After doing so, we will convert our “courses” object to the “keys” array: // convert object to keys arrayconst keys = Object.keys(courses);// print all keys console.log(keys); In the next step, we will iterate using the “courses” object using the “keys” array. Here, we have used the “forEach()” loop for the iteration: // iterate through object keys.forEach((key, index) => { console.log(`${key}: ${courses[key]}`);}); Have a look at the output of the provided example in the below-given image:

 Iterate through Objects by utilizing Object.values() method

The JavaScript Object.values() method is opposite to the Object.key() method and was embedded in the ES8. The Object.values() method outputs an array comprising the property values of the added object. After that, you can iterate through the object values by utilizing an array looping method such as JavaScript forEach() loop.

 Example: Iterating through Objects by utilizing Object.values() method

This example will show you how to iterate using the Object.values() method through an object value. For this purpose, we will create a “birds” object having four properties “crow”, “sparrow”, “parrot”, and “pigeon” with their respective values: const birds = { crow: 1, sparrow: 2, parrot: 3, pigeon: 4 }; Now, to iterate through the values of the “birds” object, we will invoke the Object.values() method while passing the “birds” object as an argument: // iterate through object valuesObject.values(birds).forEach(val => console.log(val)); Check out the below-given output of the object values iteration:

 Iterate through Objects by utilizing Object.entries() method

Another ES8 method that can be utilized for iterating through the objects is “Object.entries()” method. When you invoke the Object.entries() method by passing the created object as an argument, it will return two elements in each inner array. The first array element will represent the object property, and its corresponding value will be stored in the second element.

 Example: Iterating through Objects by utilizing Object.entries() method

To use the Object.entries method() in your JavaScript program, create an object with some properties and their values. For instance, we have created a “birds” object which has four properties: const birds = { crow: 1, sparrow: 2, parrot: 3, pigeon: 4 }; Now, to iterate through the “object” values, we will pass our “birds” object as an argument to the “Object.entries()” method and store the return value in the “entries” variable: // iterate through object valuesconst entries = Object.entries(birds); console.log(entries); As you can see from the below-given output, the “Object.entries()” method has returned four inner arrays, where each array is storing a single property of the “birds” object along with its value: To iterate through the array, which is returned by the JavaScript Object.entries() method, you can also use the “forEach()” method or the “for..of” loop. To use the for..of the loop, you have to write out the following code after creating the required birds object: for (const [key, value] of Object.entries(birds)) { console.log(`${key}: ${value}`);} With the help of the “for..of” loop, we have successfully iterated over the “birds” object, which can be seen in the output: In this case, if you want to utilize the “forEach()” method for the same purpose, then invoke the Object.entries() method while passing the created object as an argument and then call the “forEach()” method. The forEach() method will return the object properties or keys and their respective values: // forEach() methodObject.entries(birds).forEach(([key, value]) => { console.log(`${key}: ${value}`)});

 Conclusion

Using for..in loop, Object.key() method, Object.values() method, Object.entries() method, you can iterate through the objects. The for..in loop, Object.entries() method, and Object.keys() method are used to iterate through the object key pair values whereas, the Object.values() only iterates through the property values of an object. This write-up discussed the methods of iterating through objects. Moreover, the procedures related to object iteration such as for..in loop, Object.keys() method, Object.values() method, and Object.entries() method are also demonstrated with examples.

How to add an Event Handler to an Element

The event handler, in general, is that piece of code that controls events. It dictates the software about the actions it should take when an event occurs. JavaScript event handlers invoke a particular piece of code when a specific event occurs to an HTML element. You can add one or more than one event handler to an HTML element that will operate on a relevant piece of code on the basis of the kind of event that occurs to the HTML element. This write-up discusses in-depth ways of adding event handlers to an HTML element.

 How to add an Event Handler to an Element

JavaScript provides addEventListener() that allows you to add an event handler to an HTML element. This method binds an event to an HTML element, moreover, it adds an event handler to a particular HTML element without overwriting any event handler that already exists on that element.

 Syntax

element.addEventListener(eventtype,eventListener);

 Example

Suppose you want to add an event handler that binds click event to an element. <!DOCTYPE html><html><body> <button id="button"><strong>Click me</strong></button> <p id="tutorial"></p><script> document.getElementById("button").addEventListener("click", functionName);function functionName() { document.getElementById("tutorial").innerHTML = "YOU CLICKED ME!";}</script></body></html> In the above example, we are creating a button using the following piece of code. <button id="button"><strong>Click me</strong></button> Using the addEventListener() method, we are attaching a click event to the button. document.getElementById("button").addEventListener("click", functionName);function functionName() { document.getElementById("tutorial").innerHTML = "YOU CLICKED ME!"; When you click the button, a note will be appear telling you that you just clicked the button. We have shown the output below.

 More About Event Handlers!

1.It is possible to add various event handlers or various event handlers of the same kind to a particular element.

 Example

Following is an example of adding two keypress events to an input field using addEventListener() method. <!DOCTYPE html><html><body><input id="myInput"><script>var x = document.getElementById("myInput"); x.addEventListener("keypress", firstFunction); x.addEventListener("keypress", secondFunction);function firstFunction() { alert ("First keypress event happened!");}function secondFunction() { alert ("Second keypress event happened!");}</script></body></html> In the above example, the following piece of code adds two keypress events to an input field. function firstFunction() { alert ("First keypress event happened!");}function secondFunction() { alert ("Second keypress event happened!");} When you press a keyboard key while inside the input field, the first keypress event will occur. After you click OK in the dialogue box, second keypress will happen. 2.Event handlers can be added to DOM objects as well. 3.Event handlers dedicate the behaviour of events on how these react on bubbling. 4.To increase the readability, JavaScript splits up from HTML markup when addEventListener() method is used. 5.While using the addEventListener() method, you can also use event bubbling or event capturing but it is totally optional. In event bubbling the event of inner most element is operated first and the event of outer most element later. However, in event capturing the event of the outer most element is operated first and the event of inner most element later. Syntax for using event bubbling and event capturing is as follows. element.addEventListener(event, function, useCapture); Note: In the above syntax, by default the parameter value is false that means event bubbling will occur but if you pass the parameter value as true then event capturing will happen.

 Example

Following is an example of bubbling propagation. <!DOCTYPE html><html><body><p id="para1">This is bubbling propagation.<br><br><button id="button1">Click me!</button></p><script> document.getElementById("button1").addEventListener("click", function() { alert("You clicked the button!");}, false); document.getElementById("para1").addEventListener("click", function() { alert("You clicked the paragraph!");}, false);</script></body></html> In the above example, we are creating a <p> element as a parent element and <button> element as child element. <p id="para1">This is bubbling propagation.<br><br><button id="button1">Click me!</button></p> Using then used to add a click event using addEventListener() method along with bubbling propagation. document.getElementById("button1").addEventListener("click", function() { alert("You clicked the button!");}, false); document.getElementById("para1").addEventListener("click", function() { alert("You clicked the paragraph!");}, false); When you execute this program, and click the button first then bubbling propagation will operate the click event on the button (inner-most element) first and the paragraph (outer-most element) later. Here is the output. Now when you will click OK, bubbling propagation will perform click event on the paragraph. Using the same example, if you pass the parameter value as true then capturing propagation will happen. <!DOCTYPE html><html><body><p id="para1">This is bubbling propagation.<br><br><button id="button1">Click me!</button></p><script> document.getElementById("button1").addEventListener("click", function() { alert("You clicked the button!");}, true); document.getElementById("para1").addEventListener("click", function() { alert("You clicked the paragraph!");}, true);</script></body></html> If you click the child element (button) first then capturing propagation will operate click event on paragraph (outer-most element) first and button (inner-most element) later. We have shown the output below. After clicking OK, click event will happen on the <button> element. 6.It is also possible to remove an event handler using the removeEventListener() method.

 Conclusion

JavaScript provides addEventListener() method that allows you to bind an event handler to an element. You can attach various event handlers of the same kind to a particular element, moreover, besides HTML elements you can also add event handlers to DOM objects. You can also add bubbling propagation and capturing propagation using addEventListener() method. This write-up discusses in detail, approaches of adding event handlers to an element using JavaScript along with suitable examples.

Function Parameters and Arguments

In JavaScript, the terms parameters and arguments of a function are often used interchangeably, although there exists a significant difference between them. When we define a function, the function parameters are included. You can also specify a variable list while declaring a function, and these variables are known as function parameters. However, when we invoke or call the created function by passing some values, those values are called “function arguments”. This write-up will discuss Function parameters and arguments. Moreover, we will also talk about the function Parameters rules, Adding function parameters, Unmatched function parameters, Default function parameters, Argument Object, Pass by value and Pass by reference, with the help of examples. So, let’s start!

 Function Parameters

In JavaScript, the parameters are the variables we list in the function declaration. When we create a function, we take parameters, which are included in the function definition. Multiple parameters can be added inside parentheses, separated by commas as shown in the below-given syntax: function name(parameter1, parameter2, parameter3) { //body of the function} Here, “x” and “y” are parameters in the following “addNumber()” function: function addNumber(x, y){ return x+y;}

 Function Arguments

The value we pass to a function is known as the argument of a function. Arguments are provided to the function when we call it. For instance, in the following example, “5” and “6” are the arguments passed to the “addNumber()” function: var sum=addNumber(5,6) console.log(sum) When we call the addNumber() function, JavaScript will create two new variables, “x” and “y,” according to our defined parameters and then initializes them by utilizing the arguments. After doing so, the body of the function will be executed:

 Function Parameter Rules

Here are some of the rules that are defined for parameters: You can define any number of parameters for your JavaScript function, and the number of arguments added does not have to be matched with the number of parameters. You can also define default parameter values while declaring functions. Parameters are evaluated from left to right.

 Adding function parameters

You can add multiple parameters to your JavaScript function according to your requirements. For example, we will create a “firstFunc()” function which will have zero parameters and return a string “This is linuxhint.com”: // 0 parametersfunction firstFunc() { return "This is linuxhint.com";} The second function we will create is “secondFunc()”. It will take one parameter, “name” and upon calling this function, a string will be returned comprising the passed “name” argument: // 1 parameterfunction secondFunc(name) { return "Hi " + name;} Next, we will create the third function named “addNumber()”. The addNumber() function will take two number arguments passed in the “x” and “y” parameters, and it will return their sum: // 2 parametersfunction addNumber(x, y) { return x + y;} Now firstly, we will call the firstFunc() function. Then, we will pass “John” as a name in “secondFunc()”, and lastly, “2” and “3” are passed as arguments to the addNumber() function: console.log(firstFunc()); console.log(secondFunc("John")); console.log(addNumber(2,3)); Now, have a look at the output of the created function:

 Unmatched function parameters

The JavaScript function will not throw any error when the arguments you have passed are greater or less than the number of parameters. For instance, we have created an “addNumber()” function which has two parameters, “x” and “y”: function addNumber(x, y) { return x + y ;} When we call our “addNumber()” JavaScript functionwithout passing any arguments, it will not throw any error. However, it will initialize the added parameters as “undefined”. In the other case, if the number of arguments exceeds the number of parameters, the JavaScript interpreter will ignore the remaining arguments. In a situation, when no argument is passed, both “x” and “y” parameters will be initialized as “undefined”: console.log(addNumber()); When you pass a single argument, it will be passed to the “x” parameter, and “y” will be initialized as “undefined”: console.log(addNumber(10)); Now, when we pass three values as arguments, “x” and “y” will be initialized with the first two values, and the third argument will be ignored: console.log(addNumber(10,20,30)); The following image will show you the code and the output related to the above-given cases:

 Default function parameters

JavaScript also permits you to configure the function parameters with the default values. These values are added in function declaration using the assignment operator “=”. For instance, in the below-given “addNumber()” function, we have assigned “0” to both of our “x” and “y” variables. Now, these variables will be initialized to zero if we do not pass any argument while calling the “addNumber()” function: function addNumber(x=0, y=0) { return x + y ;}

 Argument Object

Another method exists to access the arguments inside our function, which is “Arguments Object”. The Arguments Object comprises the argument values in an object with a mechanism similar to arrays. Let’s help you understand this concept with an example.

 Example: Using Argument Object

In the below-given “sum()” function, we have declared three parameters: x, y, and z. We can access the values of the passed arguments using the “arguments” array, such as to access the “x” argument value, we will utilize the “0th” element of the arguments array “arguments[0]”. Now, execute the below-given code and check out the result of the sum() function and the accessed arguments array elements: function sum(x, y, z) { console.log(arguments[0]); console.log(arguments[1]); console.log(arguments[2]); return x+y+z; } sum(4, 5, 6);

 Pass by Value and Pass by Reference

Reference types and the value types are the two JavaScript types. Number, symbol, string, boolean, null, undefined, bigint are all value types, and the rest of the types come under reference types. In JavaScript, value types are passed with the help of “values”. For instance, in the following example, we have created an “x” variable having “2” value: x=2 We will pass our “x” variable to the “someFunc()” function. At the time of calling the “someFunc()”, a new “y” variable will be created, which is specified as a parameter. The variable “y” will copy the values passed of the argument “x”. Now, whatever changes we will make to the “y” variable value, it will not affect the value of the variable “x”: function someFunc(y) { y=4 console.log(y) } someFunc(x) console.log(x) Execute of the above-given code will show you the following output: Now, let’s move to the pass-by-reference concept. For this purpose, firstly, we will create an “employee” object, as an object is considered a reference type: let employee = { firstName: 'John', lastName: 'Smith'}; When we call the “doSomething(employee)” function, a new variable “obj” will be created, which will get the content from the “employee” object. Both “employee” and “obj” variables refer to the same object. However, in such a case, when you make any changes in “obj”, it will also affect “employee”, as both are pointing or referring to the same object: function doSomething(obj) { obj.firstName = 'Peter';} doSomething(employee); console.log(employee.firstName); From the output, you can see that the “firstName” is changed to “Peter”:

 Conclusion

In JavaScript, parameters and arguments are the two terms associated with the function. Function parameters are the variables specified in the function definition, and function arguments are the values passed as arguments. This write-up discussed Function parameters and arguments. We have also talked about the function Parameters rules, adding function parameters, Unmatched function parameters, Default function parameters, Argument Object, Pass by value, and Pass by reference, with the help of examples.

How to Convert Arrays to String?

Strings and arrays are two different variable types and we often need to convert arrays into a string for fulfilling our desired tasks in programming. For some specific functions, arrays are converted into strings. Therefore,, a defined method is used for the conversion of arrays into a string. JavaScript allows returning the values of an array into a string by using the “toString()” method. In this article, the conversion of arrays into a string is discussed.

 toString() Method

toString() is a built-in single method that is used for the conversion of arrays into strings. It converts different types of arrays into strings such as Convert arrays into a string Convert mix arrays into a string Convert nested arrays into a String Convert a nested array of objects into a string The given example shows the conversion of an array into a string.

 How to convert an array of numbers into a string

In this example, we can see that after the use of a function every element of an array is separated by commas and returned as a string. const newArray = [3, 2, 8]; newArray.toString(); // expected output: 3,2,8

 How to convert an array of strings into a string

In the second example, let’s take the array of strings and pass it to the toString() method. This example concatenates all strings in an array together by using a single comma-delimited string, and returns the array values in form of string. const strArray= ['a', 'b', 'c']; strArray.toString(); // expected output: a,b,c

 Conversion of an array with different datatypes into a string

In the previous two examples, you learn to convert arrays of numbers and strings into strings separately. Arrays may contain mixed data types as well, which means an array contains both numbers and strings in one array. Therefore, in the next example, we learn how to convert an array with different datatypes into a string.

 Example

const mixArray = ['15', 22, 'Mark']; mixArray.toString(); // expected output: 15,22,Mark The above example uses the toString() method to convert a an array with different datatypes into strings.

 How to convert Nested Arrays to String

JavaScript handles nested arrays in an interesting manner. First, look at the following code that shows an array with nested elements. const arrInArr = [ '15', 22, [ 'Mark', 4 ] ]; arrInArr.toString(); // expected output: 15,22,Mark,4 The elements of an array will be flattened when the toString() method is called in an array. The resultant string consists of all the elements of the original array associated with all elements of the nested array. The toString() method separates each element of the array using a comma.

 How to convert a nested array of objects into a string

Now the question is that, what if you are working with a nested array of objects? The behavior of function will be changed in the case of objects. It can be better to show it by an example. Take a look at the following example: const objInArr = ['15', 22, { name: 'Mark', age: 40 } ]; objInArr.toString() ; // expected output: 5,32,[object Object] You can see that an array of nested objects result in a string value after using the toString() function. The resulting expression shows the nested array values as [object, object]. It is due to the type of underlying objects.

 Conclusion

The toString() method is used for the conversion of array to string javascript. The toString() method takes array values and returns a combined single string as a result. In this article, we learned how to convert different types of arrays into a string along with detailed examples. toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.

Shift operators

Shift operators are used for the manipulation of data by shifting the bits of the first operand from one side to another. Shift operators are used to perform logical operations on bits because mathematical operations are not applicable on bits. Shift operators are faster, simple, and more clear than mathematical operations. In this tutorial, we will discuss the shift operators and learn about the use of these operators and explain the different types of shift operators with examples and codes.

 Shif Operators

Three types of shift operats are given below: Left shift Zero-fill right shift Right shift (Sign Propagation) The types and symbols of these operators are given in the table. Representation of Operators
Name of OperatorsSymbol of Operator Example
Left Shift<<y << z
Sign-propagating right shift>>>y>> z
Zero-fill right shift >>y >>z
Furthur, we are going to explain the types of all shift operators with code examples.

 Left Shift Operator

Left shift operator adds the zero bits on the right side and discards the bits from the left side. To have a better understanding, have a look at the diagram below: An example of a left shift operator is given below programming: let a = 8; let b = 1; result = a << b; console.log(result); // 16 ( 00000000000000000000000000010000 )

 Zero-fill right shift Operator

This operator adds the zero bits on the left side and discards the bits from the right side. To have a better understanding, have a look at the diagram below: An example of a zero-fill right shift operator is given below programming: let a = 8; let b = 1; let c = -3; result = a >>> b; result1 = c >>> b; console.log(result); console.log(result1);

 Sign-propagating right shift

Sign propagation takes one bit from the left side and shifts it to the right side. In sign propagation, bits added from the left are dependent upon the number of signs. To understand it better take a look to the following example: An example of sign propagation right shift is given below programming: let a = 8; let b = 1; let c = -3; // 11111111111111111111111111111101 result = a >> b; result1 = c >> b; console.log(result); console.log(result1);

 Conclusion

Shift operators are used for shifting the bits of the first operand from one side to another. three shift operators are used: Left shift, Zero-fill right shift, and Sign-propagating right shift. In this tutorial, we learned about all types of shift operators that are used and their working. All operators are well explained by examples and codes.

JavaScript Keyboard Events

Interactions between HTML and JavaScript are defined by events. From loading a page to pressing any key or resizing a window etc are all considered events. JavaScript events are included in HTML DOM version 2 and version 3. There is a vast category of JavaScript events that can happen by manipulating a web page through a user or the browser, however, in this write-up, we will be talking specifically about events that happen using a keyboard.

 JavaScript Keyboard Events

The events that happen when a keyboard key is pressed are referred to as JavaScript Keyboard Events and these are a part of KeyboardEvent Object. The events that fall under the category of keyboard events are: onkeydown Event onkeypress Event onkeyup Event Here we will throw light on these above-mentioned events in detail.

 1.onkeydown Event

When a keyboard key is being pressed the onkeydown event happens. It bubbles and is also cancelable. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and are included in DOM version 2. Syntax The syntax of the onekeydown event is as follows HTML Syntax <element onekeydown=”functionName()”> JavaScript Syntax object.onkeydown = function(){script}; JavaScript addEventListener() Syntax object.addEventListener(“keydown”, script);

 Example

<!DOCTYPE html><html><body><input type="text" id="tutorial" onkeydown="functionName()"><script>function functionName() { alert("You just pressed a key while inside the input field!");}</script></body></html> In the above example, an input field has been created. While inside the input field, when the user presses a keyboard key, the onkeydown event will trigger, and the background color of the input field will change to pink.

 Output

Before pressing a keyboard key. After pressing a keyboard key inside the input field.

 2.onkeypress Event

When a keyboard key is being pressed the onkeypress event happens. It bubbles and is also cancelable. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and are included in DOM version 2. Syntax The syntax of the onekeypress event is as follows HTML Syntax <element onekeypress=”functionName()”> JavaScript Syntax object.onkeypress = function(){script}; JavaScript addEventListener() Syntax object.addEventListener(“keypress”, script);

 Example

<!DOCTYPE html><html><body><input type="text" id="tutorial" onkeypress="functionName()"><script>function functionName() { document.getElementById("tutorial").style.backgroundColor = "pink";}</script></body></html> In the above example, an input field is being created. When a user presses a keyboard key while being inside the input field, the onkeypress event will happen and the background color of the input field will change to pink. Output Before pressing a key. After pressing a keyboard key, the input field background color changes to pink.

 3.onkeyup Event

When a keyboard key is released the onkeyup event happens. It bubbles and is also cancelable. This event supports all HTML tags other than <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> and are included in DOM version 2. Syntax The syntax of the onekeyups event is as follows HTML Syntax <element onekeyup=”functionName()”> JavaScript Syntax object.onkeyup = function(){script}; JavaScript addEventListener() Syntax object.addEventListener(“keyup”, script);

 Example

<!DOCTYPE html><html><body><input type="text" id="tutorial" onkeydown="keydownFunction()" onkeyup="keyupFunction()"><script>function keydownFunction() { document.getElementById("tutorial").style.backgroundColor = "pink";}function keyupFunction() { document.getElementById("tutorial").style.backgroundColor = "yellow";}</script></body></html> In the above example, both onkeydown and onkeyup events are demonstrated. An input field is being created. When you press a key, the onkeydown event gets triggered and the input field background color will turn to pink and when you release a key the onkeyup event will trigger and the background color will become yellow. Output When the user presses a key in the input field. After releasing the key.

 Conclusion

Events that occur due to pressing a keyboard button are referred to as JavaScript mouse events. Events that are classified into the category of JavaScript keyboard events are onkeydown Event, onkeypress Event, onkeyup Event. All these events have different purposes, and they are discussed in detail along with appropriate examples, in this write-up.

JavaScript Object Accessors (Getters and Setters)

Object accessors properties are methods that are used to get or set the value of an object. “get” is the keyword that is utilized for defining a getter method that retrieves the property value, whereas “set” defines a setter method for changing the value of a specific property. When we want to access a property of our JavaScript object, the value return by the getter method is used, and to set a property value; the setter method is invoked, and then we pass the value as an argument that we want to set. This write-up will discuss the JavaScript Object Accessors. Moreover, we will also demonstrate examples related to Getter, Setter, and Object.defineProperty() JavaScript methods. So, let’s start!

 JavaScript Getter method

Getter methods are used for accessing the property value of a JavaScript object. The “get” keyword is added before the function name, indicating that it is a “getter” method that will access a specific property of the created object.

 Example: Creating and using JavaScript Getter method

This example will show you how to create and use the JavaScript getter method for any object. First of all, we will create an “employee” object having two properties: firstName as “john”, and lastName as “albert”: const employee = { firstName: 'john', lastName: 'albert', }; In the next step, we will create a “getFirstName()” getter method that will access the “firstName” property of our “employee” object. Remember that you have to define the getter method within the object definition block, not outside of it: get getFirstName() { return this.firstName;} After creating the “getFirstName()” JavaScript getter method for the employee object, you will now have two choices for accessing the “firstName” property. Either you can directly access it by utilizing the “firstName” property with the employee object or by accessing the “getFirstName” getter method as a property: //accessing data properties console.log(employee.firstName);// accessing getter method console.log(employee.getFirstName); Have a look at the following image to see the output of the provided code:

 JavaScript Setter method

In a JavaScript program, the Setter methods change an object’s property value. It must take only one formal parameter. The “set” keyword is added to specify that it is a JavaScript “setter” method that will change the value of any particular object property.

 Example: Creating and using JavaScript Setter method

Firstly, we will create a simple “employee” object that comprises two properties, “firstName” and “lastName” as follows: const employee = { firstName: 'john', lastName: 'albert',}; Next, we will define our setter method “changeFirstName” that will be utilized for changing the “firstName” of the employee object. Note that you have to perform this operation within the object definition block: //accessor property(setter) set changeFirstName(newFirstName) { this.firstName = newFirstName;} Now, we will check out the property value of the “firstName” and then set it to the “Jim” using the “changeFirstName” setter method of our JavaScript employee object: console.log(employee.firstName);// changing object property using a setter employee.changeFirstName = 'Jim'; console.log(employee.firstName); Check out the below-given image for viewing the output:

 JavaScript Object.defineProperty() method

Apart from the JavaScript getters and setters, there also exists the “Object.defineProperty()” method that can be used for accessing and changing the object properties. The “Object.defineProperty()” method assists in adding getters and setters for any JavaScript object.

 Syntax of Object.defineProperty()

To use Object.defineProperty() method in your JavaScript code, you have to follow its syntax: Object.defineProperty(objectName, propertyName, objectDescriptor) Here, in the “objectName” argument you have to add the created object Name; the second argument “propertyName” represents the property. Lastly, the “ObjectDescriptor” argument is used for describing the object property.

 Example: Creating and using JavaScript Object.defineProperty() method

This example will create a getter and setter method using the Object.defineProperty() method. For this purpose, firstly, we will create an “employee” object having a “firstName” property: const employee = { firstName: 'Stepheny'} Now, to define a getter method using Object.defineProperty(), we will specify “employee” as our object, “getName” as property. Then we will add the related description followed by the “get” keyword in the body of the Object.defineProperty() method: // getting propertyObject.defineProperty(employee, "getName", { get : function () { return this.firstName; }}); Similarly, you can also define a setter function for the “employee” object by setting the property name as “changeName”. After doing so, add the “set” keyword and define the body of your setter method: // setting propertyObject.defineProperty(employee, "changeName", { set : function (value) { this.firstName = value; }}); To access the Object.defineProperty() getter method, we will use the “employee” object property name “getName” which is added as the second argument in the Object.defineProperty() method: //getting the property value console.log(employee.getName); For setting or changing the firstName of the employee, we will assign the new firstName to “employee.changeName” property: // changing the property value employee.changeName = 'Julie'; console.log(employee.firstName); Here is the complete JavaScript program with its output:

 Conclusion

JavaScript object accessors are defined using getter and setters methods. The getter method returns the property value, whereas an argument is passed to the setter method, assigning that specific value to the JavaScript object property. This write-up discussed the JavaScript Object Accessors. Moreover, examples related to Getter, Setter, and Object.defineProperty() JavaScript methods are also demonstrated in this article.

How to Change HTML Element’s Content

HTML acronym of Hyper text mark up language is used to create structure of web pages you see on internet everyday. Meanwhile, Javascript is a well-known scripting language used to perform dynamic operations on web pages to make them more interactive. An interesting HTML feature is HTML DOM short for Document Object Model. It is a programming API for HTML and XML documents. It is basically used to provide a logical structure to the documents. It defines how an HTML document can be assessed and manipulated. It permits JavaScript to alter the content of HTML elements. In this write-up we will discuss:
    Altering the content of HTML elements using JavaScript Altering HTML attribute value using JavaScript Usage of the document.write() method

 Altering the content of HTML elements using JavaScript

The innerHTML property is the quickest approach to alter the content of HTML elements. It iis explained in detail below:

 innerHTML Property

The innerHTML property alters the content of an HTML element. In order to use this method use the following syntax.

 Syntax of using innerHTML

document.getElementById(id).innerHTML = new HTML Let us demonstrate the innerHTML property with an example. Example 1 <!DOCTYPE html><html><body><p id="para1">This is a paragraph</p><script> document.getElementById (para1). innerHTML = "This is a new paragraph!";</script><p>The above paragraph was changed by innerHTML property</p></body></html> In the above example, we are manipulating the <p> element by using the JavaScript innerHTML property. The paragraph has an id=”para1″. The HTML DOM uses this id to get the particular element and then change the content of <p> tag using innerHTML property. In this way the old paragraph is overwritten by the new paragraph. The output of the above example is as follows: We can also change the <h> elements using this method. Lets do an example in which the innerHTML property changes the <h2> element using its id. Example 2 <!DOCTYPE html> <html> <body> <h2 id= "head2">Lets change this heading</h2> <script> const element = document.getElementById ("head2"); element.innerHTML = "This heading replaces the old one"; </script> <p>The old heading has been changed</p> </body> </html> In the above example HTML DOM uses the id=”head2″ to get the <h2> element and the innerHTML property changes the content of the element. The output is as follows. Now let us discuss how we can change the value of an HTML attribute using JavaScript.

 Altering Attribute Value

Using the the attribute name we can alter the value of HTML attribute.

 Syntax

The syntax is shown below: document.getElementById(id).attribute = new value Lets demonstrate the above syntax using a suitable example. <!DOCTYPE html><html><body><img id= "image1" src= "dogpic.jpg"><script> document.getElementById("image1").src="catpic.jpg";</script><p>The dog image is changed to cat image</p></body></html> In the above example, HTML DOM gets the img element by id=”image1″ then the JavaScript src attribute chages from a dogpic.jpg to a catpic.jpg. Moving on to the last method which is document.write() method.

 document.write()

document.write() is used to write HTML expressions or JavaScript code directly into HTML output stream. It will overwrite the document if you use this method after loading the HTML document. Lets try an example. <!DOCTYPE html> <html> <body> <p>This is a paragraph</p> <script> document.write(window.screen.height); </script> <p>This is another paragraph</p> </body> </html> In the above example, the document.write() method shows the height of window screen as output.

 Conclusion

HTML DOM provides certain properties that allow JavaScript to alter contents of HTML elements. In order to alter the contents of HTML elements, the innerHTML() property is used. You can also change the attribute value of HTML elements by directly using the attribute name. Meanwhile, the document.write ( ) property is used to write HTML expressions or JavaScript code directly into HTML output stream. This article discusses these properties in detail with relevant examples.

Error Handling

Error handling in JavaScript is a method that is utilized to handle the encountered error and maintain the flow of your JavaScript code. It also permits the execution of abnormal statements that exists within a program. JavaScript offers various errors handlers that process the encountered error and execute the code that is added for handling the error. For instance, when you divide any non-zero value by zero, it will yield infinity. This is an error that is handled by the JavaScript exception handling procedure. This write-up will discuss Error Handling. Moreover, the procedure of using try-catch block, throw statement, and the try-catch-finally blocks, their syntax, and examples related to error handling are also provided. Before moving towards the error handling procedure, let’s check out the type of JavaScript errors.

 Types of Errors

There exist three types of errors that might occur while executing a JavaScript program: Logical Error: Logical error is a type of error which encounter when your program contains any logical error that terminates it abnormally and does not provide the desired output. Runtime Error: A Runtime error encounters during the execution of your JavaScript code. Error handlers are then utilized to handle the Runtime error. Syntax Error: A syntax error occurs when you make any kind of mistake in the JavaScript pre-defined syntax.

 Error Handling Statements

If any error occurs, the following statements blocks are used to handle it: try block: coding, the “try” block comprises the code that can throw an error. catch block: To handle the encountered error, you have to write out the code in the “catch” block. These kinds of statements are mainly used for displaying customized messages or to log errors. finally block: Regardless of whether an error occurs or not, the final block code will always get executed. It can be utilized for resetting variables that are changed because of the try block. You can also use the “finally” block for completing the remaining tasks of your JavaScript program.

 Error Handling using try-catch block

In the JavaScript programming language, a try-catch block is used for handling the code that is prone to error. The try-catch block firstly checks the program if there exist any errors. Then, if any error occurs, it takes the specified action to handle it. A good JavaScript programming approach is to keep complex code within the try-catch block. Now, check out the below-given flowchart to understand the working of the “try-catch” block:

 Syntax of try-catch block

To use a try-catch block, you have to follow the below-given syntax: try{ //try code block }catch(error){ //catch code block } The code which is added in the “try” block will be executed first. If any error encounters, the “catch” code block will be run next, otherwise, it will be ignored.

 Example: Using try-catch block for handling error

First of all, we will define an array “x” in our try block and then we will call the “document.write(x)” method for displaying the “x” array elements. Next, the added “document.write(a)” lines will invoke the catch block, as we have not defined variable “a” in our code and we are trying to fetch its value. In this case, the catch-block will handle the encountered error by displaying its related information in the alert box: <html><head> Exception Handling</head><body><script>try{ var x= ["10","12","6","25"]; document.write(x); document.write(a);}catch(e){ alert("The encountered error is "+e.message);}</script></body></html> The execution of this JavaScript program will display the elements of the “x” array while showing an alert for the encountered error “a is not defined”:

 Error Handling using throw statement

You can also use the “throw” statement for defining custom errors. When the JavaScript interpreter will execute the throw statement, it will shift the control towards the catch block and will not run any code present after the “throw” statement.

 Syntax of throw statement

Now, check out the syntax of using throw statement in the try-catch block try{//try code blockthrow Exception;}catch(error){//catch code block } Here, “Exception” is added to define custom exceptions which can be a number, string, or any boolean value.

 Example: Using throw statement for Error Handling

In this example, we will use the throw statement for creating a custom “a throw keyword” error: <html><head>Exception Handling</head><body><script>try { thrownewError('a throw keyword');}catch (e) { document.write(e.message); }</script></body></html> The execution of the above-given code will show you the following output:

 Error Handling using try-catch-finally block

In your JavaScript code, once the try and catch statements are executed, the optional “finally” block runs after that. Whether the exception is thrown or not, the “finally” block code will run

 Syntax of try-catch-finally block

Have a look at the syntax of the try-catch-finally block: try{//try code block}catch(error){//catch code block}finally{//finally code block } Here, the “try” code block checks for the errors, then the “catch” block will be executed to handle the encountered error, and lastly, the “finally” code block contains the executable code which will always run, regardless of any error that occurs or not.

 Example: Using try-catch-finally block for Error Handling

In the following example, we will define a try-catch-block. In the first step, first of all, we have defined a variable “x”in the try block. After that, the try block will check if the added value for the “x” variable matched with the value specified in the “if” condition. It will print out the “okay” string when the “if” condition is true. In the other case, the added “catch” block will be executed. Lastly, the code written in the “finally” block will display the string “value of x is 10” as output: <html><head>Exception Handling</head><body><script>try{ var x=10;if(x==10) document.write("okay ");}catch(Error){ document.write("Error found "+e.message);}finally{ document.write("Value of x is 10 ");}</script></body></html> As you can see from the output, the code written in the “try” and “finally” block is executed for the added logic in our JavaScript program:

 Error Objects

In JavaScript, the “Error Object” is a type of built-in object that provides information related to the encountered error. It comprises two useful properties: “name” and “message”. The “name” property of the error object is utilized to set or return the error name, whereas the “message” sets or returns the error message which can be a string.

 Error Name Values

The error name property can return the following values in the JavaScript: Eval Error: This type of error name value indicates that an error occurred in the “eval()” function. Range Error: If you use a number in your JavaScript code that is outside of the range of the legal values, a “RangeError” is thrown. Reference Error: If you refer to a variable that has not been declared anywhere in your program, a “ReferenceError” is thrown. Syntax Error: Syntax Error indicates that you are trying to execute code having syntax error. Type Error: If you utilize a value that is outside of the expected data types, then a “TypeError” is thrown. URI Error: The use of illegal characters in a URI function can be the reason behind the URI Error.

 Conclusion

For handling errors, the procedure of using try-catch block, throw statement, and the try-catch-finally blocks are well explained along with their syntax, and related examples in this write-up. According to your requirements, you can use any of the given statements to handle the encountered error, maintain the flow of your JavaScript program, and ease the code development process.

How to convert Booleans to Numbers

Like other programming languages, JavaScript does support the Boolean datatype. The Boolean data type contains one of the values True/ON and False/OFF. Various methods exist for converting a Boolean to a number using JavaScript. When converting a Boolean into a number, you would either get 0 or 1 instead of False/OFF or True/ON respectively. This article provides a demonstration of converting a Boolean into a number: Before getting into the details, here we are using VS Code to write JavaScript code.

 How to convert a Boolean into a number

This section provides the usage of various functions and operators that will be used to convert a Boolean into a number.

 How to use Unary operator to convert a Boolean to a number

The unary operator is just prefixing a “+” sign to a Boolean value and the Boolean value will be converted to the respective number. The Unary operation is carried out using the following syntax: Syntax +<boolean-value>; For instance, the following code converts false and true Boolean values to relevant numbers: Code var n = +true; //storing the +true in n variable console.log(n); // printing the n variable var m = +false; // storing the +false in m variable console.log(m); // printing the m variable Output

 How to use Ternary operator to convert a Boolean to a number

The ternary operator (?) is used by following the syntax provided below: Syntax <boolean-value> ? 1:0; The following line of code uses the ternary operator to convert false and true to 0 and 1 respectively: Code var q=true ? 1:0; //declaring q variable console.log(q); //printing the q variable var w = false ? 1:0; //declaring w variable console.log(w); //printing the w variable Output

 How to use Number() function to convert a Boolean to a number

The Number() function can be used to convert a Boolean value to a number, and it works on the basis of following syntax: Syntax Number(boolean-value); The code provided below shows that Boolean value is passed to convert it to a number: Code var e=Number(true); //declaring e variable console.log(e); //printing the e variable var r =Number(false); //declaring r variable console.log(r); //printing the r variable Output

 How to use Arithmetic Operators to convert Boolean to a number

Interestingly, the arithmetic operators can also be used to convert a Boolean to a number.

 Using * to convert a Boolean to a number

The syntax provided below converts the Boolean to number: <boolean-value>*1 The following lines of code converts the Boolean value “False” to respective number (0) and “True” to “1”: Code var a =false*1; //declaring a variable console.log(a); //printing the a variable var s =true*1; //declaring s variable console.log(s); //printing the s variable Output

 Using + to convert a Boolean into a number

To convert a Boolean into a number using + operator, you have to use “0” with that Boolean value: We have practiced “+” to convert Boolean to a number as shown below: var d =false+0; //declaring d variable console.log(d); //printing the d variable var f =true+0; //declaring f variable console.log(f); //printing the f variable Output

 Conclusion

JavaScript provides support of various functions and operators to convert a Boolean into a number. This article contains the functionality of the Number() function, and operators such as AND, OR, Unary, Ternary and Arithmetic. All these operators and functions are used to convert a Boolean into a number. A Boolean number has value True/ON and False/OFF; therefore, when a Boolean is converted into a number it would return 1 or 0 for True/ON or False/OFF respectively.

How to Convert Dates to Numbers

In the life of a JavaScript developer, formatting date or time is a common task. There exist various reasons to show or convert the current, past, and future times. You can convert dates to numbers if you want to calculate the time between two dates, calculate the age of someone, or find the execution time of a program. In JavaScript, you can convert dates to numbers with the help of the “.getTime()” function of the “Date” Object. Don’t know how to use the “Date.getTime()” method? No worries! This article will assist you in this regard. So, let’s start!

 What is Date object

In JavaScript language, the “Date” object is a built-in data type utilized to work with dates and timings. It also offers various methods for storing date in a variable, getting current time and date, formatting the date according to the user’s locale, and performing different arithmetic operations. By utilizing the “new” keyword, you can create a Date object in four different forms. To know more about it, check out the below-given syntax of the Date objects.

 Syntax of Date object

Check out the following syntax for creating a new Date object with the current time and date: new Date() You can also create a new Date object by passing the milliseconds as arguments: new Date(milliseconds) To specify the year, month, day, hour, minutes, second, and millisecond, for a Date Object, use the below-given syntax: new Date(year, month, date, hour, minute, second, millisecond) You can also pass “dataString” as a parameter for the representation of the Date Object: new Date(dataString)

 How to access components of Date object

Several methods exists for accessing the components of Date object such as getMonth(), getHours(), getFullYear(). More specifically, we will talk about the “getTime()” method of the date object.

 Date object getTime() method

The getTime() method outputs a numeric value related to the specified date in universal time. It returns the number of milliseconds since Epoch or January 1, 1970 (00:00:00). The getTime() function of the Date object is also used for assigning time and date to another Date object. It also works in the Universal Time Zone, so if the getTime() function is called from multiple timezones, it will show the same results.

 Syntax of getTime()

Here is the syntax of getTime() method: Date.getTime()

 How to convert Dates to Numbers

Using the Date.getTime() method, you can easily convert the dates into numbers. Want to try it out? If yes, then firstly define a Date Object in your JavaScript code. const date1 = new Date(); console.log(date1); In the above-given code, the “new Date()” constructor is utilized for creating a new Date “date1” object, and then it will output the current time and date with the help of the “console.log()” function: Next, to convert the date into number, we will use the “getTime()” method in this way: const result = date1.getTime(); console.log(result); The execution of the above-given code will return the number of milliseconds between January 1, 1970 (EcmaScript epoch) and the current date: You can also specify a “dataString” for converting the added date to numbers. For instance, in the below-given example, we will convert the “January 25, 1998 12:35:32” to numbers: var x = new Date('January 25, 1998 12:35:32'); var y = x.getTime(); console.log(y); When you execute the provided code, it will show the converted number as output:

 Conclusion

This write-up demonstrated how to convert dates to numbers. Using the Date object getTime() method, you can easily convert the dates into numbers to calculate the time between two dates, calculate the age of someone, or find the execution time of a program. We have discussed the Date.getTime() method, its syntax, usage, and procedure of using it to convert the dates to numbers, in this writeup.

How to convert numbers to strings

In terms of altering the behavior of web pages at the client side, Javascript is the most prevalent scripting language. It supports a lot of built it functions that assist in fulfilling various requirements of the user. The .toString() method of JavaScript allows converting the numbers to strings. It accept variables as well as direct numbers. This guide provides a detailed demonstration of converting numbers to strings. Before getting into depth, we recommend a few packages that assist in executing the JavaScript files.

 Prerequisites

The following set of prerequisites are recommended to carry out the operations specified in this guide: – Latest version of Visual Studio Code Download VS Code – Either the latest version of Nodejs or you can use your browser to test the code Navigate to nodejs.org to download the latest available version

 How the toString() method works

The functionality of any method or function depends on the syntax followed by that method/function. The syntax of the toString() method of JavaScript is provided below: <variable>.toString(); A variable consisting of a numerical value can be passed and it must be placed at <variable> location of the above-mentioned syntax. Moreover, .toString() method can be used on a number directly (in place of <number>) by using the following syntax: <number>.toString(); The .toString() method accepts a single argument named as base that is used to convert the number to a specific base and then it is converted to string. The base can be 2 (to convert to binary numbers), 8(for octal number), 10(for decimal number), or 16(for hexadecimal numbers): <number>.toString(base)

 How to convert Numbers to strings

This section provides a few examples which exercise the use of the .toString() method of JS. So, let’s start it:

 Example 1

Firstly, we have created a .js file in Visual Studio Code and named it as numtostr.js. The code written inside is written and described below: Code var n = 99; console.log(typeof(n)); var st = n.toString(); console.log(typeof(st)); – A number (99) is stored in a variable named n – The second line of the code will print the type of variable n – Another variable (st) is used to store the value of .toString() method (that is applied on n variable) – For verification, we have obtained the datatype of the st variable as well using the console.log(typeof(st)) method Image of the Code and Output

 Example 2: Passing number to .toString() method

A number can directly be passed to the .toString() method. For instance, the code provided below passes the number 10 to the .toString() method. The description of the code is shown below: – A variable str is declared which stores the number 10 applied on .toString() method – console.log method is used to get the type of the variable Code var str = (99).toString(); console.log(typeof(str)); Image of code and its output

 Example 3: converting a “number to binary” and “then to a string”

You can use the .toString() method to convert a number into a binary and then to a string. To do so, the following code converts n variable to an equivalent binary number and then to a string: Code var n = 22; //declaring a variable console.log(typeof(n)); //getting the type of n var st = n.toString(2); //converting n to binary and then to string console.log(st); //printing the st variable console.log(typeof(st)); //getting the type of st variable Note: The text written after “//” is considered as comments. Image of code and output

 Example 4: Converting “number to octal” and “then to string”

A number can be converted to octal base number and then to a string by using .toString() method. A new variable is created named as oct and is passed to .toString(8) method to convert it to octal and string simultaneously. var oct = 22; //declaring a variable console.log(typeof(oct)); //getting the type of oct variable var st = oct.toString(8); //converting oct to octal and then to string console.log(st); //printing the st variable console.log(typeof(st)); //getting the type of st variable Image of code and output Similarly, as in Example 4 and Example 5, the .toString(10) and .toString(16) methods convert the number to decimal and hexadecimal numbers respectively. Moreover, it will convert those numbers to string as well.

 Conclusion

The .toString() method of JavaScript is used to convert numbers of various categories to a string value. This article provides a demonstration to convert numbers to strings. By going through this guide, you have learned the generic working mechanism of the .toString() method. Moreover, for better understandings, several examples are provided that exercise the .toString() method.

How to Convert Strings to Numbers

Data Management is one of the essential concepts in programming. As a result, JavaScript provides various functions for parsing data types, which permits you to easily convert the data format. For instance, if you want to perform any mathematical operations on a string comprising a number, you have to convert that string into a number first. For this purpose, there exist many JavaScript methods such as parseInt(), parseFloat(), Number(), Math.floor(), and Math.ceil(). This write-up will demonstrate the method of converting strings to numbers using all of the mentioned functions. So, let’s start!

 How to Convert Strings to Numbers using parseInt() method

In JavaScript, the “parseInt()” function is utilized for converting a string to a number. It takes “string” and “radix” as parameters and then converts the added string into an integer. In the parseInt() function, the radix is added to specify the numerical system you want to use. For instance, the radix “8” indicates that the added number in the string will be converted from octal to decimal base. This method will output “NaN” Not a Number if the specified string does not include a numeric value.

 Syntax of parseInt()

Now, check out the syntax of parseInt() function for converting strings to numbers: parseInt(String, Radix) In the above-given syntax, add the “String” which you want to convert as a first argument. Next, add a base as radix which is optional. This function will return a numeric value resulting from the string to number conversion.

 Example: Converting Strings to Numbers using parseInt() without radix

In the first example, we will try to convert the “22a” string to a number using the parseInt() function. For this purpose, we will write out the following code in our console window: myString = '22a' console.log(parseInt(myString)) The parseInt() function will convert the value of “myString” to its corresponding number and show you the result with the help of the console.log() function:

 Example: Converting Strings to Numbers using parseInt() with radix

As mentioned earlier, you can also add the base as “radix” for the conversion. For instance, we have defined “22” as a string and then set its radix as “8” in the parseInt() function. The result will be calculated as (2+2*8), which is “18”: myString = '22' console.log(parseInt(myString, 8))

 How to Convert Strings to Numbers using parseFloat() method

If you want to convert a string into a floating-point number, you have to use the parseFloat() JavaScript function. It only returns the number found at the starting of the specified string that has been parsed until the parseFloat() function comes across a character that is not a number.

 Syntax of parseFloat()

Here is the syntax of parseFloat() function for converting strings to numbers: parseFloat(String) The parseFloat() function accepts a single parameter as a “String” you want to add for conversion purposes.

 Example: Converting Strings to Numbers using parseFloat() method

The following example will convert our “testString” having the value “224.56b” to a number using the parseFloat() function and the output of the parseFloat() function can be seen in the console window: let testString = parseFloat("224.56b") ; console.log(testString);

 How to Convert Strings to Numbers using Number() method

The Number() function is used for converting JavaScript objects or variables to numbers. It can also be utilized for converting the added string to the number. This method will output “NaN” if the added string is not capable of being converted to a number.

 Syntax of Number()

Have a look at the syntax of the Number() function: Number(Object) This Number() function will convert any data type JavaScript object to a number and return its value.

 Example: Converting Strings to Number using Number() method

In the below-given example, we will convert the “testString” JavaScript variable to a number using the “Number()” function: let testString = Number("101.11"); console.log(testString); The output declares that we have successfully converted the added string to a number:

 How to Convert Strings to Numbers using Math.floor() method

The Math.floor() function returns the largest integer value less than or equal to the number that is passed. This function also takes strings and converts them to integers.

 Syntax of Math.floor()

Math.floor(Value) The above-given Math.floor() function will take the specified string as “Value” and then convert it to a number.

 Example: Converting Strings to Number using Math.floor() method

Now, we will utilize the Math.floor() function to convert the “101.11” string to a number: let testString = Math.floor("101.11"); console.log(testString);

 How to Convert Strings to Numbers using Math.ceil() method

The Math.ceil() function is utilized to display the smallest integer greater than or equal to the specified number. You can also utilize this function for converting strings to numbers.

 Syntax of Math.ceil()

Math.ceil(Value) The Math.ceil() function can take the added string as “Value” and then convert it to a number.

 Example: Converting Strings to Numbers using Math.ceil() method

For instance, to convert the “578.99” string to number, we will use the Math.ceil() function in the following way: let testString = Math.ceil("578.99"); console.log(testString); The Math.ceil() function will round off the “578.99” string to the “579” number:

 Conclusion

To convert strings to numbers several methods are used such as parseInt(), parseFloat(), Number(), Math.floor(), and Math.ceil() and this write-up contains the detailed description and examples of all these methods. All of the given methods are easy and simple to use. You can utilize any of them for converting your selected string into a number.

How to display output

You may need to display output from your JavaScript code in certain situations. For instance, when you want to send a message to your browser console to assist you in debugging errors or checking the value of a variable using your JavaScript code, and so on. There are different ways to generate and display output, including writing output to an HTML element, displaying output in alert boxes, or the browser console window. This write-up will demonstrate how to display output using console.log(), document.write(), document.getElementById(), and window.alert() function. So, let’s start this guide!

 What are the possibilities to display output

You can display output using any of the following ways: To display output in the browser console, you can use the “console.log()” function. To write out into HTML and display its output, you can use the “document.write()” function. To write into an HTML element and display its output, you can use the “document.getElementById()” function with the “.innerHTML” property. To display output into an alert box, you can use the “window.alert()” function.

 How to display output using console.log()

In JavaScript, the “console.log()” function is utilized for displaying any output or printing the values of any variable defined in the program. The “log()” method in console.log() takes the parameter which comprises the data you want to output. Most JavaScript developers use the specified function to list errors and debugging purposes.

 Syntax of console.log()

Here is the syntax of console.log(): console.log("Parameter") The “console.log()” function accepts a “Parameter,” which can be any message, object, or array, and it then returns or outputs the value of the given parameter to the console window.

 Example: Displaying output using console.log()

In the below-given example, we will use the console.log() function to output the “This is linuxhint.com” message on our webpage. For this purpose, we will create a “testfile.html” file in our favorite code editor such as VS Code, then write out the following code in it: <!DOCTYPE html><html><body><script> console.log("This is linuxhint.com");</script></body></html> After adding the code, press “CTRL+S” to save the added code in the “testfile.html”. Next, click on your file and open it in your favorite browser by double-clicking on the HTML file. A blank web page will open for your “testfile.html” file. From the right-click menu, choose the “Inspect” option to open up the Developer tools of your browser directly: Now, move to the “Console” tab of the developer options. It will display the message which we have added as a parameter to the “console.log()” function:

 How to display output using document.write()

In JavaScript, the “document.write()” function is used for inserting any content or JavaScript code in a document. The “document.write()” function removes all existing content from the HTML document and replaces it with the new content added as a parameter. This method is mainly employed for testing purposes.

 Syntax of document.write()

Now, check out the syntax of the document.write() function: document.write(Exp1,Exp2,...) The “document.write()” function can contain multiple parameters. The expression arguments such as “Exp1” and “Exp2” will be displayed as output in their added sequence.

 Example: Displaying output using document.write()

In the following example, as soon as our web page gets loaded, the “document.write()” function will clear all data of the web page and rewrite it with the content which we have added as the parameter: <!DOCTYPE html><html><body><h1>linuxhint</h1><script> document.write("This is linuxhint.com");</script></body></html> As we have added “This is linuxhint.com” as a parameter in our “document.write()” function, it will display the following output:

 How to display output using document.getElementById()

The “document.getElementById()” is utilized for returning the Element object, whose “Id” gets matched with the provided string. The Element Ids are useful for quickly accessing the specified element, and thus they can be used with the “.innerHTML” property to write or display its output.

 Syntax of document.getElementById()

Let’s have a look at the syntax of document.getElementById() function: document.getElementById(id) Here, the attribute “id” defines the HTML element which can be used for inserting or writing output within the specified element:

 Example: Displaying output using document.getElementById()

In the following example, we have added an element with the id “test”. After doing so, the “document.getElementById(test)” method will select our HTML element having id=test”. Then, the “.innerHTML” property is added to write out the specified string in it: <!DOCTYPE html><html><body><h1>Linuxhint</h1><p id="test"></p><script> document.getElementById("test").innerHTML = "This is linuxhint.com";</script></body></html> The below-given image indicates that we have successfully added the “This is linuxhint.com” string in our selected element:

 How to display output using window.alert()

The window.alert() method displays output or any information to the user. It shows the added message in an alert box having the “OK” button. The alert box forces the user to read the displayed message, and the user cannot access the web page until the alert box is closed.

 Syntax of window.alert()

To use alerts for your web page, follow the below-given syntax: window.alert("Parameter") Here, in the “Parameter”, pass the information you want to display in the added alert box.

 Example: Displaying output using window.alert()

In this example, we have added an alert box that will pop up on the web page showing “This is linuxhint.com” as its content: <!DOCTYPE html><html><body><h1>Linuxhint</h1><script> window.alert("This is linuxhint.com");</script></body></html> When the window.alert() pop up will appear on our web page, then any code written after the window.alert() does not get executed until you close the alert by pressing the “OK” button:

 Conclusion

This write-up discussed how to display output in JavaScript using console.log(), document.write(), document.getElementById(), and window.alert() functions. The procedure of using console.log(), document.write(), document.getElementById(), and window.alert() functions for displaying output are also demonstrated in this article. Based on your preferences, you can generate and display output, by writing output to an HTML element, displaying output in alert boxes, or the browser console window.

JavaScript Date Get Methods

In JavaScript, several methods exist that assist you in retrieving the current system date and time. A “Date” object can return values in milliseconds, seconds, minutes, hours, days, months, and years. You can use the JavaScript Date Get methods for getting the current date and time from the JavaScript and then display it in an HTML document. Moreover, a digital clock can be created by utilizing the Date get methods of JavaScript. This write-up will discuss the JavaScript Date get methods and their usage in the JavaScript code. Moreover, the examples related to each Date get method such as getTime(), getFullYear(), getMonth(), getDay(), getDate(), getHourse(), getMinutes(), and getSeconds() will be provided. So, let’s start!

 JavaScript Date getTime() method

The Date getTime() method outputs a numeric value related to the specified date in universal time. This method will return the number of milliseconds since Epoch or January 1, 1970.

 Example: Using JavaScript Date getTime() method

To use the JavaScript getTime() method, firstly create a “Date” object and then call the getTime() method: const date1 = new Date(); date1.getTime(); The output of the above-given code will show you the number of milliseconds from January 1, 1970, to the current date and time:

 JavaScript Date getFullYear() method

The Date getFullYear() output the four-digit value (yyyy) representing the current year of a date in local time.

 Example: Using JavaScript Date getFullYear() method

For instance, to display the current year as output, we will execute the following code: const date1 = new Date(); date1.getFullYear(); Here, we have created a new Date “date1” object, and in the next line, we have called “getFullYear()” method, which will return the current year value:

 JavaScript Date getMonth() method

Another built-in method for the Date Object is “getMonth()” method. The “date.getMonth()” returns a number between 0-11, where 0 represents “January” and 11 represents “December”.

 Example: Using JavaScript Date getMonth() method

To know more about the working of the Date getMonth() object, write out the following code in your console window: const date1 = new Date(); date1.getMonth(); From the below-given image, you can see that the output is showing “0,” which indicates that the current month is “January”:

 JavaScript Date getDay() method

According to the local time, the “getDay()” Date object method displays the day of the week, and it returns a value between 1 to 7, where 1 represents “Monday,” and 7 represents “Sunday”:

 Example: Using JavaScript Date getDay() method

If you want to get the numerical value representing the current day in any of your programs, then you can utilize the below-given code: const date1 = new Date(); date1.getDay(); The execution of the added code will return “5,” which declares that today is “Friday”:

 JavaScript Date getDate() method

getDate()” built-in JavaScript method is used to get the date in numerical format. This Date object method will return a value between 1 to 31.

 Example: Using JavaScript Date getDate() method

You can utilize the following code if you are required to return the number of the month’s day: const date1 = new Date(); date1.getDate();

 JavaScript Date getHours() method

The Date object getHours() method is used to get the day’s hours for the current or specified date object value. It returns a value between 0 to 23.

 Example: Using JavaScript Date getHours() method

To use JavaScript getHours() method, firstly create a “Date” object, and then call the “getHours()” function in this way: const date1 = new Date(); date1.getHours();

 JavaScript Date getMinutes() method

Similar to the getHours() method, you can also check out the minutes of the current hour in numerical format. The JavaScript Date getMinutes() method permits you to do so and returns a number between 0-59.

 Example: Using JavaScript Date getMinutes() method

The below-given code will print out the minutes comprising the current system time: const date1 = new Date(); date1.getMinutes();

 JavaScript Date getSeconds() method

When we have discussed getting the hours and minutes values from the created date object, you must wonder if there is any built-in JavaScript function that will display the seconds of the current minute as a number. The “getSeconds()” method is the answer to your question, and it helps you know about the seconds of the current minute as numbers having values between 0-59.

 Example: Using JavaScript Date getSeconds() method

To explore the functionality of JavaScript Date getSeconds() method, you can create a Date object and then utilize it to call out the “getSeconds()” method: const date1 = new Date(); date1.getSeconds();

 Conclusion

The methods to get the date are getTime(), getFullYear(), getMonth(), getDay(), getDate(), getHours(), getMinutes(), and getSeconds() for getting current time, year, month, day, date, hours, minutes, and seconds respectively. This write-up discussed the JavaScript Date get methods and their usage in the JavaScript code. Moreover, the examples related to each Date get method such as getTime(), getFullYear(), getMonth(), getDay(), getDate(), getHourse(), getMinutes(), and getSeconds() are also provided in this article.

JavaScript Getting Started Guide

As a newbie in programming, most people select JavaScript as their starting point. For a good reason, JavaScript is a widely utilized programming language with several applications. Previously, it was only used to increase the interactivity of the web pages through animation and form validation. However, JavaScript is now employed in various domains such as mobile app development, server-side development, and game development. Some people become eager to execute their JavaScript code, and they do not know where to start. With that in mind, this write-up will provide a complete JavaScript getting started guide. Moreover, we will also discuss some best Websites, Browsers, and IDEs that you can use for running your JavaScript programs. So, let’s get started with JavaScript!

 Getting started with JavaScript using Websites

An online coding sandbox is the quickest way to get started with JavaScript. The online coding sandboxes or the websites also permit you to do coding with the functionality of checking its output side by side. It offers you a controlled test environment for the fastest deployment of the software. Most JavaScript developers use the online coding sandboxes for testing purposes and easier automation. If you want to utilize an online coding box to get started with JavaScript, here are some of the top options: Plunker, Codesandbox, JSFiddle, JS.do, Codepen, and JSBin. For instance, we will use the JSBin coding sandbox to execute our JavaScript code. To do so, firstly, we will navigate to its website: To show you how JSBin operates for executing JavaScript, we will write out the below-given code in the left-side input section: <!DOCTYPE html><html><body><h1>linuxhint</h1><script> document.write("This is linuxhint.com");</script></body></html> As soon as we complete our coding, its result will be shown by the JSBin in its adjacent output section:

 Getting started with JavaScript using Browsers

You can use multiple browsers to execute your JavaScript code, such as Google Chrome, Mozilla Firefox, Microsoft Explorer, and Apple’s Safari. To narrow it down, most JavaScript developers utilize Mozilla Firefox with the excellent Firebug extension and Google Chrome with its developer tools for writing and testing the JavaScript code. JavaScript engines are embedded in all of these popular web browsers. So, you can progress from online coding sandboxes to executing JavaScript straight into your Browser if you want to boost your coding game. We are using Google Chrome to get started with JavaScript on our system. For this purpose, we will open up the “Developer tools” by selecting the “Inspect” button from the right-click menu: Then, move to the “Console” tab in between the other options: After doing so, type out your JavaScript code and press “Enter” to view its output:

 Getting started with JavaScript using IDE

Although you can use various browsers and online coding sandboxes for running JavaScript, an Integrated Development Environment (IDE) makes it much easier to debug the code. It also offers support to the application lifecycle management system. The best IDEs which you can utilize for getting started with JavaScript are as follows: Visual Studio Code: Visual Studio Code is a freely available, cross-platform IDE for the developers, which comprises features such as smart code completion, built-in Git integration, and code debugging within the editor. It offers powerful JavaScript, CSS, HTML, and JSON editors. Additionally, you can install snippets, debuggers, linters, and various other JavaScript tools using its extensions. WebStorm: If you are looking for a tool you can use to handle the trickiest part of your JavaScript code, you should try WebStorm. It is considered the smartest IDE for JavaScript and its related technologies. Using WebStorm, you can enjoy a fantastic development experience by detecting potential problems in the code with the built-in debugger and refactoring the entire codebase. It is also well-integrated with JavaScript Flow type checker and linters. Atom: Atom is another well-known IDE for getting started with JavaScript. It is a highly customizable and flexible source code editor built using JavaScript, HTML, CSS, and the integration of Node.js. If you are a beginner JavaScript developer, you may find ATOM easy to use and understand, and it also permits you to write your JavaScript code efficiently. We have provided all of the essential information about getting started with JavaScript. Now, you can experiment with this language to observe its functionality. We recommend you start a small JavaScript project according to your requirements, and then seeing it through to the completion stage will give you a lot of knowledge and polish your JavaScript coding skills.

 Conclusion

This article comprises a complete JavaScript getting started guide. The procedure of using different Websites, Browsers, and IDEs for getting started with JavaScript is also discussed in this article. Using JavaScript, you can create a website with a console-like appearance and provide the finest GUI to visitors. Based on your preferences, you can utilize the online coding sandboxes or the modern web browsers such as Google Chrome, Mozilla Firefox, and Safari and IDEs for getting started with JavaScript.

Methods of accessing JavaScript Properties

In JavaScript, an object can be defined as a collection of unordered properties associated with it. It also offers three different methods for accessing the Object properties, all of which are useful and can be used in combination. The methods we are talking about are Dot property accessor, Square property accessor, and Object destructuring. This guide will discuss the specified methods for accessing the JavaScript object properties. Moreover, we will also demonstrate the syntax, usage, and examples related to Dot property accessor, Square property accessor, and the Object destructuring methods. So, let’s start!

 Dot property accessor for JavaScript properties

The first and the most common method of accessing JavaScript properties of an object is to use the dot property accessor. This method is only utilized for accessing the valid identifiers of the declared object. Syntax of the dot property accessor is given below: objectName.propertyName Here, you can add the “objectName” and “propertyName” of the created object you want to access.

 Example: Using Dot property for accessing JavaScript properties

We will create an “employee” object and define its “name” property. const employee = { name: 'John'}; After doing so, you can access the added property by writing out the following code in the console window: employee.name; In the above-given code, the dot property accessor will access the “name” property of the “employee” JavaScript object:

 Accessing valid and invalid identifiers for JavaScript properties

When you specify the property name as a valid identifier, the dot property accessor functions correctly., a valid identifier comprises digits (0-9), special characters ($, _), and Unicode letters. However, sometimes the added properties are not valid identifiers. For instance, in the below-given code, the “name-1” and “5” are the invalid identifiers, so the dot property accessor will not operate perform its functionality in the given code: const employee = {'name-1': 'john','5': 'five'}; employee.name-1; employee.5; Here, both of the “employee” object properties are invalid identifiers as the “name-1” contain “-” and the other property starts which a number “5,” which is an indication for the invalid identifier: JavaScript also offers solutions for every encountered problem, including the usage of invalid identifiers. If you have added the properties for your object having unique names, then you can utilize the square property accessor for accessing those properties.

Square property accessor for JavaScript properties

Square property accessor is used to access the object properties you can not access with the dot property accessor. It is mainly used for accessing the invalid identifier and properties of the array object. Check out the syntax of the square property accessor for accessing the JavaScript object properties: objectName[propertyName] Here, you have to specify the “objectName” and its related property in the “propertyName” which you want to access.

Example: Using Square brackets for accessing JavaScript properties

Now, we will access the “name-1” and “5” invalid identifiers with the help of the Square brackets accessors: const employee = {'name-1': 'john','5': 'five'}; console.log(employee['name-1']); console.log(employee[5]); The below-given output declares that we have successfully accessed the “name-1” and “5” JavaScript properties of our “employee” object:

 Object destructuring method of accessing JavaScript Properties

In the Object destructuring method, the destructuring assignment permits you to assign properties related to the object’s variables and arrays. To access the JavaScript object properties using the object destructuring, you have to follow the following syntax: { propertyName } = objectName Here, enclose the “propertyName” in the “{}” curly braces and then add the “objectName” for the assignment purpose.

 Example: Using Object destructuring method for accessing JavaScript properties

To teach you the usage of the object destructing method, firstly, we will create an “employee” object having a “name” property. After doing so, we will add the destructuring object line, which is “const { name } = employee;”. This destructuration will define a variable “name” having the value of employee object property: const employee = { name: 'john'};const { name } = employee; console.log(name); The below-given output declares that we have successfully accessed the “name” property of our “employee” JavaScript object with the help of the object destructuring method:

 Conclusion

Dot property accessor, Square brackets accessor, and Object destructing are the methods of accessing JavaScript properties. The Dot property accessor is used to access the valid JavaScript identifier of an object. Whereas the Square brackets accessor is utilized for accessing the invalid identifier or dynamic property name. Also, the Object destructing method can assist you in accessing object properties. We have demonstrated Dot property accessor, Square property accessor, and Object destructuring methods of accessing JavaScript properties with examples in this article.

Assignment Operators | Explained with Examples

Assignment operators are a crucial part of computer programming that are used to allocate the value of the left operand to the right operand or in simple words assign values to variables. Assignment operators perform logical operations like, bitwise logical operations or operations on integral operands or boolean operations. Javascript makes use of multiple assignment operators. Here we have listed JavaScript assignment operators for you.

 Assignment (=)

The assignment operator is used for the purpose of assigning a value to a variable. Example: let a=10; console.log(a); Output: 10

 Addition Assignment (+=)

The addition assignment operator is used to add the value of the right operand to the left operand and allocates the resulting value to the variable. Example: let x=2; console.log(x+=2); // or x = x + 2 Output: 4

 Subtraction Assignment (-=)

The subtraction operator subtracts the value of the right operand from the left operand and allocates the resulting value to the variable. Example: let a=10; console.log(a-=2); // or a = a - 2 Output: 8

 Multiplication Assignment (*=)

The multiplication assignment multiplies the value of the right operand with the left operand and assigns the resulting value to the variable. Example: let x=2; console.log(x*=2); // or x = x * 2 Output: 4

 Division Assignment (/=)

The division assignment divides the variable value by the right operand and assigns the resulting value to the variable. Example: let a=4; console.log(a/=2); // or a = a / 2 Output: 2

 Remainder Assignment (%=)

The remainder operator returns the remainder that is left as a result of dividing one operand by another. Example: let x=3; console.log(x%=2); // or x = x % 2 Output: 1

 Exponentiation Assignment (**=)

Exponentiation operator is used to raise the value of the variable to the right operand. Example: let x=3; console.log(x**=2); // or x = x ** 2 Output: 9

 Left Shift Assignment (<<=)

The left shift operator pushes a particular number of bits to the left and the resulting value is assigned to the variable. Example: let a = 5; // 00000000000000000000000000000101 a<<=2; // 00000000000000000000000000010100 console.log(a); Output: 20

 Right Shift Assignment (>>=)

The right shift operator pushes a particular number of bits to the right and the resulting value is assigned to the variable. Example: let y = 5; // 00000000000000000000000000000101 y>>=2; // 00000000000000000000000000010100 console.log(y) Output: 1

 Unsigned Right Shift Assignment (>>>=)

The right shift operator pushes a particular number of bits to the right and the resulting value is assigned to the variable. Positive numbers are shifted to the right with same effect as the right shift operator, meanwhile, for negative numbers empty bits are replaced by zeros. Example: let x = 5; // 00000000000000000000000000000101 x>>>=2; // 00000000000000000000000000010100 console.log(x) Output: 1

 Bitwise AND Assignment (&=)

This operator uses the binary codes of the both left and right operand and performs AND function then assigns the result to the variable. Example: let x = 5; // 00000000000000000000000000000101 x &=3; // 00000000000000000000000000000011 console.log(x); Output: 1 // 00000000000000000000000000000001

 Bitwise XOR Assignment (^=)

This operator uses the binary codes of the both left and right operand to perform XOR and assigns the result to the variable. Example: let a = 5; // 00000000000000000000000000000101 a ^=3; // 00000000000000000000000000000011 console.log(x); Output: 6 // 00000000000000000000000000000110

 Bitwise OR Assignment (|=)

This operator uses the binary codes of the both left and right operand to perform OR and assigns the result to the variable. Example: let a = 5; // 00000000000000000000000000000101 a |=3; // 00000000000000000000000000000011 console.log(x); Output: 7 // 00000000000000000000000000000111

 Conclusion

The assignment operators are useful when assigning values to the operands or performing different arithmetic operations on the variables in an expression. There are numerous assignment operators which are used for various purposes. This tutorial highlights these operators along with their examples.

Function Hoisting

Hoisting is the default behavior in JavaScript, which moves all declarations before code execution to the top of the global or local scope. It is a JavaScript property that permits you to use a variable or function before declaring it. It does not matter where you have declared the variables or functions in your JavaScript code; they can be easily moved to the top of their scope. Want to use function hoisting? If yes, then you are at the right post! This write-up will discuss the function hoisting, variable hoisting, and hoisting precedence. Moreover, the difference between the function expression and function declaration hoisting will also be demonstrated with the help of examples. So, let’s get started!

 Variable Hoisting

As variable hoisting is linked with the function declarations hoisting and function expression, we will discuss variable hoisting first. In variable hoisting, A variable with the keyword “var” can be declared after being utilized/accessed in the JavaScript code. The JavaScript engine moves the variable declarations at the top of the script, and this concept is known as variable hoisting. Remember that you have to declare all of your variables at the start of every scope to avoid errors or bugs. When it comes to variables and constants, the keyword “var” is permitted for the hoisting, whereas “const” and “let” are not. Now, let’s check out the below-given example to better understand the previous statement. In the below-given example, the var “c” is used in the console.log() function before its declaration. Execute the code to check out the result: c = "Hoisting"; console.log(c);var c; The output is displaying the string value of var “c,” which is “Hoisting”, indicating that the variable declaration is allowed for hoisting: In the other case, JavaScript does not allow hoisting the variable assignment. To confirm this statement, we will write out the following code and execute it in our console window: console.log(d);var d = "Hoisting"; In this example, the declaration of the variable “d” is moved to the memory in the compilation phase, so the output will show you “undefined” as the value of the “d” variable because it is printed out before the initialization:

 Function Hoisting

Similar to the variables, JavaScript hoists function declarations. In this case, the function declarations are moved to the top of your JavaScript code, and the hoisted function can be utilized before their declaration. You can define functions anywhere in your program, and that hoisted function can be invoked before its definition.

 Difference between Function expression Hoisting and Function declaration Hoisting

In JavaScript, the functions are loosely classified as Functions expression and Function declaration. When you call a JavaScript function before its declaration, it will display the output because the JavaScript interpreter hoists the function declarations. In the other case, when a function is used as an expression, it generates an error because only declarations are hoisted. In the below-given example, we will call the testFunc() function before its declaration, and it will output the string “Hi, this is linuxhint.com”: testFunc();function testFunc() { console.log('Hi, this is linuxhint.com');} That’s how JavaScript performs hoisting for the function declaration: Now, let’s utilize the “testFunc2()” as Function expression in the following JavaScript code: testFunc2(); let testFunc2 = function() { console.log('Hi, this is linuxhint.com');} In this case, a “ReferenceError” will occur stating that the added “testfunc2()” is not defined: If you execute the same code while replacing the “let” with “var”, the output will show you a “TypeError” this time because the variable “testFunc1” is used as in a function expression, and the JavaScript interpreter can only hoist the function declaration but not assignment before invoking it: testFunc1();var testFunc1 = function() { console.log('Hi, this is linuxhint.com');}

 Hoisting precedence

When you want to hoist variables and functions with the same name in your JavaScript code, then make sure you know the JavaScript hoisting precedence. Here are some points that you should keep in mind while stepping into the specified condition: The assignment of variables takes precedence over the functions declaration. Function declarations take precedence over the variable declarations. Note: Function declarations are hoisted over the variable declarations but not over the variable assignments. Now, check out the following example to understand the working of variable assignment over the JavaScript functions declaration: var test1 = 'Hi, this is linuxhint.com';function test1(a) { return (a + 'we are hoisting functions');} console.log(test1); In the above-given code, the “test1” variable assignment will take precedence, and the code will only output its value:

 Conclusion

Function hoisting is utilized for moving functions declarations to the top of their scope. Similar to the functions, the variable declarations are also used before the declaration code. This write-up discussed the function hoisting, variable hoisting, and hoisting precedence. Moreover, the difference between the function expression and function declaration hoisting is demonstrated with the help of examples.

JavaScript Statements

Statements are the building blocks of a computer program. These are instructions given to a computer to be executed by it. For example, the statement given below is a Javascript statement that sets the value of variable x equal to 5. let var x=5; Like other programming languages, JavaScript also has a bunch of statements and these follow a syntax. These statements consist of expressions, operators, values, keywords, and comments. A semicolon separates a statement from another. Suppose, let a,b,num; a=2; b=5; num=a+b; These all are statements. white spaces are ignored but if you want to add one or more white spaces for enhancing the readability of the code then it is totally your choice. It is highly recommended to add white spaces between operators (=, +, -, /). According to their usage Javascript statements are classified into different categories. Here we have listed different types of JavaScript statements for you.

 1.If…else

The if/else statements are referred to as conditional statements which are used to execute a block of code if the conditions specified in that particular block are true. Example: var x = 5;if (x > 0) { result = 'positive';} else { result = 'Not positive';} console.log(x); Output: Positive

 2.For

The for statement is used to execute a specified set of instructions multiple times. Example: for (let i=0; i<4; i++) { document.write(i); document.write("<br />");} Output: 0123

 3.For…in

The for…in statements are used to execute a loop over the properties of an object. These statements are a unique version of the for statements. Example: constperson = {fname:"John", lname:"Mike", age:20}; let text = "";for (let x in person) { text += person[x] + " ";} Output: John Mike 20

 4.Continue

A continue statement is used inside loops to terminate an iteration and the control is shifted to the beginning of a loop for the next iteration. Example: let n='';for (let i = 1; i < 5; i++) { if (i === 3) { continue; } n = n + i;} console.log(n); Output: 01245

 5. Switch

A switch statement is also referred to as a conditional statement. These statements perform certain actions that are based on specified conditions. Example: var text;var fruits = document.getElementById("myInput").value;switch(fruits) { case "Banana": text = "Banana is good!"; break; case "Orange": text = "I am not a fan of orange."; break; case "Apple": text = "How you like them apples?"; break; default: text = "I have never heard of that fruit...";} Output: Let’s say you enter ‘mango’’. The output will be: I have never heard of that fruit

 6.Break

A break statement is used to end a loop and other statements like switch and label. The control is shifted to the statement that comes right after the statement that just has been terminated. Example: let n = 0; while (n < 5) { if (n === 2) { break; } n = n + 1;} console.log(i); Output: 2

 7. Block

A block statement is used to group multiple statements. A block is defined by placing curly brackets ‘{ }’ at the beginning and the end of the group of statements(block). Example: var a = 1; let b= 1;if (true) { var a = 2; let b= 2;} console.log(x); console.log(y); Output: 21

 8.Try…catch

These statements are an exception that marks a block of code to try and specify a response. Example: try { alert('Start of try runs'); abcdef; alert('End of try (never reached)'); } catch (err) { alert(`Error has occurred!`); } Output: Error has occurred!

 9.Throw

A throw statement is a special type of user-defined statement that is used to create custom errors. Example: function doubleNumber(x) { if (typeof x !== "Number" || isNaN(x)) { throw "sorry, x is not a number"; } console.log((x *= 2));}try { let x = "X"; doubleNumber(x);} catch (e) { console.error(e);} Output: sorry, x is not a number

 10.Empty

An empty statement is used to specify that no statements will be executed. These statements are specified using just a semicolon (;). Example: const array1 = [1, 2, 3];for (let i = 0; i < array1.length; array1[i++] = 0); console.log(array1); Output: Array[0,0,0]

 Conclusion

Statements are fundamental blocks in a computer program that are used to specify instructions. JavaScript also makes use of multiple statements, each having a separate function and purpose. These statements define the basic rules of writing a JavaScript program. This tutorial enlightens its readers with various JavaScript statements along with suitable examples.

Self-Invoking Functions

JavaScript offers various useful features to its users, and the Self-Invoking function is one of them. You may not have heard the term “self-invoking” before; however, you have unknowingly used it in any of your daily JavaScript programs. Self-invoking functions are the anonymous self-executing functions that are called after their definition. These JavaScript functions can run immediately when followed by the parentheses set (). This write-up will discuss the self-invoking functions, syntax, and their working. Moreover, we will also demonstrate the difference between normal and self-invoking JavaScript functions in terms of syntax structure and working. So, let’s start!

 What are Self-Invoking Functions

In JavaScript, a “Self-Invoking” function is a type of function that is invoked or called automatically after its definition. The execution of such an anonymous function is done by enclosing it in a parenthesis set followed by another set of parenthesis. Different initialization tasks can take benefits from the usage of the self-invoking functions. For instance, Self-invoking functions can be a fantastic tool for attaching the event listeners to DOM elements of a web page. These functions can only run once, so they do not fill all sorts of CURD in the global namespace that will last according to web page lifetime.

 How Self-Invoking Functions work

As the self-invoking functions are defined anonymously, there are no local or global variables except for the declarations in the body of the functions. When you initialize a self-invoking function, it immediately runs and can be executed one time. No reference will be saved for the self-invoking function, including the return value. The self-invoking JavaScript functions are mostly utilized for scoping variables. Because these functions are anonymous, their added expression is invoked without any closure of identifier or modification of the scope.

 Syntax of Self-Invoking Functions

Now, let’s check out the syntax of the self-invoking functions: (function (parameters) { //body of the function})(arguments); Here, the “arguments” are the global object references passed to the self-invoking function. The variables you will define in the body of your self-invoking function are only accessible within the same function.

 Example: Using Self-Invoking Functions

In the following example, we will define a self-invoking function that prints out “Hi! I am calling myself” as soon as the function definition code is executed. Note that we do not have to call the defined self-invoking function ourselves: <!DOCTYPE html><html><body><p>Self-Invoking Functions</p><p id="demo"></p><script>(function () { document.getElementById("demo").innerHTML = "Hi! I am calling myself";})();</script></body></html> You can execute the above-given in your favorite code editor or any online coding sandbox; however, we will utilize the JSbin for the demonstration purpose: Now, check out the output generated by the defined self-invoking function:

 Example2: Difference between Self-Invoking function and Normal function

If you are a JavaScript beginner, then at this point, you might get confused between the syntax and functionality of a normal function and a self-invoking function. No worries! This section will assist you in this regard. The first and the basic difference between the self-invoking function and the normal function is that you have to define a proper name for a normal function and then call it by its specific name, whereas the self-invoking functions are defined anonymously and invoked automatically. For instance, to define a normal function, we will follow the below-given syntax: function functionName(){ // body of the function}; To call out the defined function somewhere in your JavaScript code, you have to utilize the function name: functionName(); Now, In the below-given code, we have defined a normal “testFunc()” function which will print out the “This is Linuxhint.com” string after calling it in the code: <!DOCTYPE html><html><body><h2>Normal Functions</h2><script>function testFunc() { document.write("This is Linuxhint.com");} testFunc();</script></body></html> Here is the output we got from the execution of the above-given code: Now, we will define a self-invoking function that will also output the same string which the normal function did. To do so, write out the following code and start the execution: <!DOCTYPE html><html><body><h2>Self-Invoking Functions</h2><p id="demo"></p><script>(function () { document.write("This is Linuxhint.com");})();</script></body></html> The output declares that the self-invoking JavaScript function has been successfully executed without being called in the program:

 Conclusion

Self-Invoking function is a type of function that is invoked or called automatically after its definition when followed by the parentheses set () and primarily used for the initialization tasks. This write-up demonstrated the syntax and usage of self-invoking functions to wrap the code inside a function scope. Moreover, the difference between normal functions and the self-invoking functions is also demonstrated with the help of some examples.

Top 5 Web File Management Platforms

Web file management is known for managing files over the web. File management in general is a procedure that permits the user to store data in an organized manner and also allows easy extraction of the data stored. Similarly, web file management allows users to upload files, documents, images, and videos safely online and in any format. The user can also share these files with other users. In order to manage your web files, the usage of a file manager is highly recommended. We are living in an era where globalization is increasing every single day. People from all kinds of professions collaborate with other people around the world on a daily basis. With such a fast-moving environment, data sharing becomes a necessity. With the advancement of technology, many platforms have been developed to aid web file management. These file managers allow you to perform the following tasks; Upload your file Download your file Rename your file Move or Delete your file Scan or Review your file Moreover, file management systems allow the owner of the files to give access to his/her files to anyone. Most of these tools are available online so there is no need to install them. In a file manager, all your files and documents that contain your data are stored in an alphabetic manner. This article reviews the top 5 popular web file management platforms.

 1. Google Drive

If you are a user seeking to manage personal web files or you own a small business that requires you to handle your files online then Google Drive is a perfect fit for you. Google Drive is a cloud-based file management system provided by Google that allows reaching your files through your computers or smartphones. It is best suited for the management of personal files however for the management of files of large-scale organizations we have enlisted some great tools below. You can use other Google platforms such as Google Docs and Google Sheets while using Google Drive. It has a handy interface and allows a maximum of 15GB of free cloud storage.

 2.Alfresco

Big businesses often need to manage the organization’s information and data in an organized and secure manner. Alfresco is a powerful content management tool for enterprises that allows inter-departmental data sharing within an organization. This tool makes document evaluation and approval very easy. Employees can save their important work files and can access them easily on their devices online. It is a tool that has been built using AI and machine learning techniques to enhance business intelligence within an organization. It provides its users with a free trial but to access its full features the users have to purchase it.

 3. eFileCabinet

eFileCabinet is a cloud-based file management system. It is an extremely powerful platform for small to medium-scale enterprises. It provides multiple features and provides limitless storage. It also has a backup feature that prevents data from being lost. The administrative side of an enterprise using this platform has the control to give full or limited access to employees. The platform allows its user to use other applications such as Word, Excel, PDF, PowerPoint, and QuickBooks. Using the tool without learning the interface can be a bit tricky since the platform provides numerous options.

 4.M-Files

M-Files is an efficient file management system that is programmed to organize data, not by storage location rather by what the data is about. It is an effective file management system that ensures that the right data reaches the right person at the right time. This efficiency of M-Files makes it an intelligent system. It allows its users to handle changes to files. This management system is designed to automate your work so that your business keeps moving without any hurdles. It is available for platforms like Windows, Mac, Android, and iOs.

 5.PDFelement

As the name suggests PDFelement deals with PDF files. It allows the users to make, convert, change, and mark PDF documents with ease. The platform permits its users to convert files from other formats like Word, Excel, and PowerPoint to PDF using this platform. It is a perfect fit for file management of small to medium-scale businesses. It provides controlled and secure handling of files. For instance, if you want to give limited access to the employees of your organization then this platform is best suited for this purpose. It has a feature that allows its user to arrange texts and images in a PDF file. This platform is supported by 20 languages.

 Conclusion

Web file management allows a user to store, upload, download, rename and scan files online. Without it running a successful business can be tricky. This article is designed to guide you about what generally web file management is, why is it necessary, why you should do it, and what platforms and tools are available that will help you to handle your files online.

How to set up the Environment for Java Programming Language

Java is an Object-oriented, general-purpose, and user-friendly language that is used to create mobile applications, game development, etc. We have to set up the environment to run the Java program. This article will provide the complete procedure to download and install the JDK, and NetBeans. Moreover, it will discuss how to set up the environment for java.

 Requirements to Run a Java Program

JDK is a development kit that contains tools like a compiler and debugger. Therefore, JDK must be installed on the system to run the code. Before heading towards JDK installation we need to understand what are the requirements to run a Java program. a machine that holds a memory of a minimum of 64 MB RAM. An Operating system like Linux, macOS, or Windows. an editor to write, compile and execute the source code of the Java program. Finally, we have to install Java JDK’s latest version.

 How to download JDK

From here this article will provide comprehensive guidance to install Java JDK on Windows 10 operating system. Open the browser and search for the “java jdk download”. Most probably the first link will be the official oracle’s link as shown in the following snippet: Click on the “oracle.com” link. The latest version of the Java JDK will appear, select the operating system of your choice. We are working on Windows operating system so we select the option accordingly as shown in the following snippet:

 How to Install JDK

Once the executable file is downloaded: Click on that file a pop-up window will appear: Allow the permission to start the installation process: Click on the Next button. In this way, the installation process will proceed further: And finally when the installation process will complete the following window will appear:

 How to setup up Environment Variable

When you are done with the installation process, open the directory where you install it. If you didn’t change the directory then the by-default path will be “C:\Program Files\Java\jdk-17.0.1”. Within this folder open the bin folder: All java related executable files will be there in the bin folder. To run all the java related commands from the command prompt we have to set the bin folder path as our environment variable path. To do this just copy the path up to the bin folder: Next, open the settings and click on the “System” option and here search for the environment variables: Select the “Edit the system environment variables”. The below-given window will appear, click on “environment variables Select the path variable and then click on the “Edit” option to set environment variables: A new pop-up window will appear, click on the new button and paste your bin folder’s path (i.e “C:\Program Files\Java\jdk-17.0.1\bin”). And lastly, click on the OK button: Now we need to set the “JAVA_HOME” variable as well because JAVA_HOME refers to the location where JDK is installed.

 How to set up JAVA_HOME Environment Variable

Now we will set the “JAVA_HOME” environment variable, for this purpose we will click on the new option A new window will appear where we will set the variable name as “JAVA_HOME” and variable value as the path up to the JDK folder “C:\Program Files\Java\jdk-17.0.1”:

 How to verify the Environment Variable

For verifying, we will open the new “command prompt” and we will type the following command: >Java -version When we will press the enter button, it will show the java version that we installed: We will pass one more command to check if the environment variable is set perfectly for the JAVA_HOME or not: >echo %JAVA_HOME% It will return the path that we gave in our java home environment variable: All the things are working perfectly and our system is ready to work with java. To run a java program we can use any editor like notepad, eclipse, NetBeans, etc. NetBeans is an easy-to-use tool that supports several programming languages. It is available for every operating system like Windows, Mac, etc. Considering these features, we will install NetBeans on our system for Java programming.

 First Step

Search for the NetBeans in the browser and download it from the “netbeans.apache.org”:

 Second Step

Select the operating system: Click on the following link that starts the downloading:

 Third Step

Now it’s time to run the downloaded file for this purpose right click on the file and run it as an admin. Allow the permission to start the installation process. After the installation process, the following window will appear: Lastly, click on the finish button and NetBeans is ready to use.

 Writing First Program in NetBeans

Now we will write a simple program to check whether NetBeans is installed properly on our system or not. We write a program to print hello world: The above code is executed successfully and printed the following output:

 Conclusion:

To set up the environment for the java programming we have to set the environment variables by going into the Settings >system >about >advanced system settings and select the environment variable to edit the path for java JDK.

Array Accessor Methods Explained with Examples

In JavaScript, there are several built-in methods available that are very beneficial in the perspective of working with arrays, such as the method that modifies the actual array is termed as a mutator method. While the method which doesn’t modify the primary/original array instead it returns some new representation for the array on the basis of the original array is termed as the accessor method. In this post, we will cover various array accessor methods like concat(), slice(), indexOf(), filter(), and lastIndexOf() method.

 concat() method

In JavaScript, the concat method is used to join the multiple arrays and as a result, it returns a new array. Let’s consider an example where we created two arrays and concatenate them in the third array, have a look at the below-given code to understand how “concat()” method works: const Array1 = [ 5,10,15,20,25 ];const Array2 = [ 30,35,40,45,50 ];const Resultant_Array = Array1.concat(Array2); console.log("The resultant array is : ", Resultant_Array); In the above-given code, the resultant array concatenates the first two arrays: The console.log function is utilized to produce the output of the resultant array on the browser’s console: The output verifies that the resultant array combines the elements of both “array1” and “array2”.

 join() method

In JavaScript, the “join()” method returns a new string by joining all the array elements within one string separated by a comma “,”. const Array1 = [ '5','10','15','20','25' ];const Resultant_Array = Array1.join(); console.log("The resultant array using Join method is : ",Resultant_Array); Here we took array1 values as string values and the JavaScript implementation of the above-given code will be: In the output, you will observe that the “join()” function returns a string that is separated by a comma. In JavaScript, anyone can separate the string elements by any other symbol of theirs choice; suppose we want to use “|” as a separated instead of comma then we will utilize it as: const Array1 = [ '5','10','15','20','25' ];const Resultant_Array = Array1.join(‘|’); console.log("The resultant array using Join method is: ", Resultant_Array); We will implement the above code as: The resultant output will be:

 filter() method

In JavaScript, the “filter()” method is utilized to filter an array on the basis of some condition. For instance, we want to filter positive numbers from an array, the code would be: const all_numbers = [5,-10,15,-20,-25,30];const Positive_only = all_numbers.filter(function(number){return number >= 0;}); console.log(Positive_only); So, in the example, we have an array that consists of both positive as well as negative numbers, and we want to filter the array and display only positive numbers. So we set a condition that will check whether “the number is greater than or equal to 0” or not, as a result: Our output shows that the “filter()” method prints the positive numbers only:

 slice() method

JavaScript utilizes the “slice()” method to copy some part of the array into some new array, and it accepts two optional parameters starting index and the last index. Let’s consider a scenario where we want only the first three elements of the array, we will do this using the slice method. The last index must be the “n+1” index, it means if you want values between index 0 to index 2 then you must write the last index as ‘3’: const Array1 = [ 5,10,15,20,25 ];const Resultant_Array = Array1.slice(0,3); console.log("The resultant array is : ", Resultant_Array); Here, we take the first index as 0, and we write the last index as 3, the slice method will exclude the last index ‘3’ and it will consider the array elements for index 0, index 1, and index 2 only. The output of the above program will be:

 indexOf() method

JavaScript utilizes the indexOf method to find the occurrence of an element in an array, and it will return -1 if the element is not found in the array. Moreover, if an array has the same element twice then the “indexOf” method will return the position of the first occurrence. Consider the below-given code to understand how “indexOf” method works: const Array1 = [ 5,10,15,15,20,25 ];const Resultant_Array = Array1.indexOf(15); console.log("The resultant array is : ", Resultant_Array); The JavaScript implementation of the indexOf method will be: The output of the above-given code will verify that the “indexOf” method returns the first instance of the searched element:

 lastIndexOf() method

JavaScript utilizes the “lastindexOf” method to find the last appearance of an element in an array, and this method will return -1 when it fails to find an element in the array: const Array1 = [ 5,10,15,15,20,25 ];const Resultant_Array = Array1.lastIndexOf(15); console.log("You searched for array index : ", Resultant_Array); Implementation of the above code will be: In Array1, ‘15’ is repeated twice, so the “lastIndexOf” method will return the index of the last occurrence of ‘15’:

 includes() method

JavaScript uses “includes()” method to search any element in an array, as a result, it will return a Boolean value : const Array1 = [ 5,10,15,15,20,25 ];const Resultant_Array = Array1.includes(15); console.log("Searched value found : ", Resultant_Array); Here we searched for ‘15’ using the “includes()” method: The “includes()” method will return the output true as ‘15’ is there in the array:

 Conclusion:

The array accessor methods perform some actions on the arrays and as a result, they return a new enhanced representation. In this post, we have learned about such methods in detail by considering some examples. Moreover, we implemented each method and noted the desired output against each method. This article will help the readers to implement the built-in array accessor methods.

Array Mutator Methods Explained with Examples

In JavaScript, the methods that modify or overwrite the original array elements are called array mutator methods, and there are many built-in methods available that can be utilized to modify the elements of the original array. For example, forEach(), reverse(), splice(), fill() and shift() method. This article will provide a thorough overview of these methods with a couple of examples.

 sort() method

Sorting array elements is very crucial, a build-in method ‘sort()’ is used to sort the unsorted array elements, by default it sorts the array elements in ascending order: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.sort(); console.log("The sorted array : ", Input_Array); We utilize the sort() function in this program and as a result, it will return a sorted array: We can also pass the comparison parameter. For instance, consider the below-given code to print the array in descending order: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.sort(function(lower, higher){return higher-lower;}); console.log("The sorted array : ", Input_Array); We passed two parameters to the function “lower” and “higher”, and “higher-lower” will return the output in descending order while “lower-higher” will return the output in ascending order:

 reverse() method

In JavaScript, the “reverse()” method is used to reverse the order of array elements, consider the below-given code to understand the working of reverse function: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.reverse(); console.log("The reverse array : ", Input_Array); The output for the reverse function will be:

 push() method

To add some new elements to the array JavaScript utilizes the “push()” method, it appends the new element at the last index of array: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.push(100); console.log("The updated array : ", Input_Array); We appended ‘100’ in the array using the push method, the output will be:

 pop() method

In JavaScript, the “pop()” method deletes the last element of the array: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.pop(); console.log("The updated array : ", Input_Array); The above code will pull out the “6” from the array and the resultant output will be:

 shift() method

The “shift()” method is used to delete the first element of the array: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.shift(); console.log("The updated array : ", Input_Array); The above code will pull out the “15” from the array and the output of this program will be:

 unshift() method

In JavaScript “unshift()” functions takes an element as a parameter and put it in the beginning of the array: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.unshift(50); console.log("The updated array : ", Input_Array); The output of the above given code will be:

 fill() method

In JavaScript, the “fill()” method replicates all the entries of an array with some specified value: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.fill(50); console.log("The updated array : ", Input_Array); Now we will implement the “fill” method on the “Input_Array”: In the output, all the elements of the array will be replicated with the ‘50’: The fill method also deals with the optional parameters. It takes three parameters, first for the specified value, second for the starting index, and third parameter for the last index. As a result, it will replicate all the elements of the array from the specified starting index to the specified last index. const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.fill(50, 1, 4); console.log("The updated array : ", Input_Array); As an example, we passed 50, 1, and 3 in the fill method, now the fill method will replace the array elements from index 1 to index 3 with 50. While the remaining indexes values will remain unchanged. Now observe the output of parameterized fill method:

 splice() method

In JavaScript, the “splice()” method is used very frequently due to its unique and specific properties. It can append or delete the elements of an array and it can perform both actions simultaneously. The “splice()” method holds three parameters: First parameter takes starting index Second parameter specifies the total number of elements to delete Third parameter is optional and it takes the element to insert in the array Now consider an example where we want to add an element in the array without deleting any existing element: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.splice(2, 0, 5); console.log("The updated array : ", Input_Array); In this example, we set the value of the second parameter as 0. In the output we observed that ‘5’ is added at index two, and it didn’t delete any existing value: Now we will consider an example where we want to delete an element from the array: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.splice(1,2); console.log("The updated array : ", Input_Array); Here in the first parameter, we specify the starting index ‘1’ and in the second parameter we write ‘2’ which specifies that delete two elements of the array. We didn’t write the third parameter because we don’t want to add a new element in the array: In the output, we noted that the values of index 1 and 2 are deleted from the array: Now we will consider an example to add and delete some entries of an array simultaneously: const Input_Array = [15, 13, 0, 12, -10, 6]; Input_Array.splice(1,2,50); console.log("The updated array : ", Input_Array); So, in this example, the “splice()” method specifies that from index 1 onwards delete two elements and insert one new element at index 1:

 Conclusion

In JavaScript, mutator methods don’t create new arrays, instead they modify the current arrays. In this article we covered various array mutator functions. We learn how mutator methods work, and we analyze that among all these methods, the pop method and the push method modify the array’s final indexes while the shift method and the unshift method modify the array’s initial indexes. Moreover, we figure out how to sort the array in ascending or descending order and how to reverse or replicate the array elements using different mutator methods.

Binary Heaps

A binary heap is an advanced level data structure concept, to understand binary heaps, you should be familiar with Binary Search Trees or Trees in general. A binary heap is, in very simple words, a partially ordered binary tree that completely satisfies the heap property

 The heap property

This property can be considered a constraint for defining a tree, a certain structure that must be followed while constructing a tree. Heap defines a relationship between the parent nodes and its child nodes, there are two types of heaps and therefore there are two types of relationship that can exist between the parent node and the child node: Max-Heap: The value of the parent nodes must always be greater or equal to the child nodes Min-heap: The value of the parent nodes must always be smaller or equal to the child nodes A representation of the Min-heap is: (Image by Wikipedia) As you can see, in the tree that the parent nodes have lower values than their child nodes Ar representation of the Max-heap is: (Image by Wikipedia) You can see that the parent nodes have values greater than their child nodes.

 Array Representation

Heaps in a programming language are represented in the form of an array, an example of the heap array constructed from the max-heap tree above is: var max-heap =[100,19,36,17,3,25,1,2,7]; When representing a binary heap in the form of an array, you use the following expression to deduce the following: Left child = i * 2 Right child = i * 2 + 1 Parent = i / 2 Where “i” stands for the index of the array. Talking about indexes, when we implement heap structures using an array, we put a “null” in the first index which is the index 0.

 Visual Representation of working of a heap

For a virtual representation of the working of a min-heap and how are the values inserted into the heap, we can head over to the heap visualizer by the University of San Francisco by clicking here Insert values into the heap, and you’ll notice how a new element is inserted into the heap due to the animation:

 Working of Heap

A Binary Heap has two main functions: First is to add the new element at its appropriate position The second function is to remove the root value

 Adding a new element in the heap

A new element is always added at the end of the array, and then it is checked against its parent and if it goes against the heap property then it is exchanged with its parent. The element is checked until it has been compared with the root node of the heap (root node is the first node of the heap).

 Removing an element from the heap

Whenever you want to remove or fetch a value from the heap, you always fetch the root node’s value. That is why this value is the smallest value if it is a min-heap and the largest value if it is a max-heap. When the root node is removed from the heap, the last node of the array takes its place, then it is compared with its child nodes to match the condition of the heap. If it doesn’t match the condition, it is replaced with its child node and then checked with further child nodes. A much better way to explain this is by using the live heap viewer as shown below: You can observe the removal process by observing the gif above.

 Implementing the binary heap

We are going to be implementing the min-heap step by step, we start of the process by creating a new function with the following lines of code: let MinHeap = function () {// Rest of the min-heap code will be present inhere} The first step is to create an array and set the value at index 0 as null: let heap = [null]; Then we are going to create the insert function using the following lines of code: this.insert = function (num) { heap.push(num);if (heap.length>2) { letidx = heap.length - 1;while (heap[idx] = 1) { [heap[Math.floor(idx / 2)], heap[idx]] = [ heap[idx], heap[Math.floor(idx / 2)], ];if (Math.floor(idx / 2) >1) { idx = Math.floor(idx / 2); } else {break; } } } } }; The following things are happening in this code snippet: A new element num is added at the last index of the array If the array length is bigger than 2 elements then we check the new element with its parent node If the element is smaller than its parent node, then it is replaced with its parent node, otherwise we deduce that the heap in in correct order If the element is replaced with its parent node in the previous step, then we again compare it with its new parent until we deduce that heap is in correct order or the element becomes the root node The next step is to implement the remove function with the following lines of code: this.remove = function () { let smallest = heap[1];if (heap.length>2) { heap[1] = heap[heap.length - 1]; heap.splice(heap.length - 1);if (heap.length == 3) {if (heap[1] > heap[2]) { [heap[1], heap[2]] = [heap[2], heap[1]]; }return smallest; } leti = 1; letleft = 2 * i; letright = 2 * i + 1; while (heap[i] >= heap[left] || heap[i] >= heap[right]) {if (heap[left] < heap[right]) { [heap[i], heap[left]] = [heap[left], heap[i]]; i = 2 * i; } else { [heap[i], heap[right]] = [heap[right], heap[i]]; i = 2 * i + 1; } left = 2 * i; right = 2 * i + 1;if (heap[left] == undefined || heap[right] == undefined) { break; } } } elseif (heap.length == 2) { heap.splice(1, 1); } else {return null; }return smallest; }; The following steps are happening in the above code snippet: We remove the root node as it is the smallest node of the heap If the heap only has two elements, then the 2nd element becomes the root node If the heap has 3 elements then the smallest out of the 2nd and 3rd element becomes the root node If the element has more than 3 elements, then the last element of the heap becomes the root node Then this new root node is compared with its child nodes and is replaced with the smaller node and is against compared with the new child nodes (for replacement we are using the object destructuring method) This process of comparing the element with the child nodes is repeated until it reaches a point where it is smaller than both of the child nodes or it becomes the last node in the array. The next step is to create a function that will display us the heap array to the console, we do that by using the following lines of code: this.show = function () { console.log(heap);}; The complete code snippet of implementing the min-heap data structure is: letMinHeap = function () { let heap = [null];this.insert = function (num) { heap.push(num);if (heap.length>2) { letidx = heap.length - 1;while (heap[idx] = 1) { [heap[Math.floor(idx / 2)], heap[idx]] = [ heap[idx], heap[Math.floor(idx / 2)], ];if (Math.floor(idx / 2) >1) { idx = Math.floor(idx / 2); } else {break; } } } } };this.remove = function () { let smallest = heap[1];if (heap.length>2) { heap[1] = heap[heap.length - 1]; heap.splice(heap.length - 1);if (heap.length == 3) {if (heap[1] > heap[2]) { [heap[1], heap[2]] = [heap[2], heap[1]]; }return smallest; } leti = 1; let left = 2 * i; let right = 2 * i + 1;while (heap[i] >= heap[left] || heap[i] >= heap[right]) {if (heap[left] < heap[right]) { [heap[i], heap[left]] = [heap[left], heap[i]]; i = 2 * i; } else { [heap[i], heap[right]] = [heap[right], heap[i]]; i = 2 * i + 1; } left = 2 * i; right = 2 * i + 1;if (heap[left] == undefined || heap[right] == undefined) {break; } } } elseif (heap.length == 2) { heap.splice(1, 1); } else { returnnull; }return smallest; };this.show = function () { console.log(heap); };}; What we need to do now is to create a new min-heap using the MinHeap function that we just created and then add elements to it using the insert and display the heap. To do this we make a new variable and map it on the MinHeap using the following lines of code: var newMinHeap = new MinHeap(); Next, up let’s add values to the heap using the following lines of code: newMinHeap.insert(34); newMinHeap.insert(61); newMinHeap.insert(138); newMinHeap.insert(82); newMinHeap.insert(27); newMinHeap.insert(35); Now, we call the show function to display the heap array onto the console: newMinHeap.show(); We get the following result on our console: As you can see, the first element of the array is null. The rest of the nodes are not bigger than their child nodes. For example, if we take the node with the value 35. The left and the right child are as: You can clearly see, the parent (35) is smaller than its left child (82) and its right child (61) as well. Similarly, every parent node is smaller then its child node, therefore we can deduce that our code is working perfectly Similarly, by just changing the condition for comparing for being the parent node being smaller than the child to the parent node being bigger than the child node we can implement the Max-heap using the following lines of code: letMaxHeap = function () { let heap = [null];this.insert = function (num) { heap.push(num);if (heap.length>2) { letidx = heap.length - 1;while (heap[idx] > heap[Math.floor(idx / 2)]) {if (idx>= 1) { [heap[Math.floor(idx / 2)], heap[idx]] = [ heap[idx], heap[Math.floor(idx / 2)], ];if (Math.floor(idx / 2) >1) { idx = Math.floor(idx / 2); } else {break; } } } } };this.remove = function () { let smallest = heap[1];if (heap.length>2) { heap[1] = heap[heap.length - 1]; heap.splice(heap.length - 1);if (heap.length == 3) {if (heap[1] < heap[2]) { [heap[1], heap[2]] = [heap[2], heap[1]]; }return smallest; } leti = 1; let left = 2 * i; let right = 2 * i + 1;while (heap[i] <= heap[left] || heap[i] heap[right]) { [heap[i], heap[left]] = [heap[left], heap[i]]; i = 2 * i; } else { [heap[i], heap[right]] = [heap[right], heap[i]]; i = 2 * i + 1; } left = 2 * i; right = 2 * i + 1;if (heap[left] == undefined || heap[right] == undefined) {break; } } } elseif (heap.length == 2) { heap.splice(1, 1); } else { returnnull; }return smallest; };this.show = function () { console.log(heap); };}; That is it, you have successfully implemented a Binary heaps

 Conclusion

Binary heaps are the parietal implementation of a binary tree having the condition of having at-most two child nodes for each parent node, and the complete structure of the binary tree. Meaning that the levels of the tree will be filled from the left-side or left-child and then the right-child. Binary heaps are part of advanced data structures, and there are two types of binary tree: one of them is called the min heap while the other one is called the max heap. In the min-heap, the parent nodes have smaller values than their child nodes and the values of the sibling nodes don’t matter. Similarly, in max-heap, the values of the parent node is always greater than their child node and the values of the sibling nodes don’t matter. In this post, we learned about heaps and their implementation in vanilla javascript and at the end we tested out our implementation.

Bubble Sort

Let suppose we have an unsorted array and we are asked to sort the array in any ascending, or descending order. Bubble sort is one of the simplest sorting algorithms that compares two side-by-side items and sorts the array. Numerous algorithms are available to sort the arrays, such as selection sort, and merge sort, etc. In this article, we will learn how to use bubble sort in order to sort the array elements.

 Working of Bubble Sort

Suppose we want to sort our array in ascending order. It starts working by comparing the left index to the right index. Initially, it will compare the values of the first two indexes of the array. The value of the 0th index will be replaced only when the 1st index carries a smaller value than the 0th index’s value. Next, it will compare the value of index 1 with the value of index 2, and so on. Suppose we have the following unsorted array: We know that in arrays indexing starts from 0. So initially, “8” is stored at the 0th index, “3” is stored at the first index, “1” is stored at the second index, and so on. Now, we have to sort this array in ascending order as shown in the below-given array: Now, we will explain the working of bubble sort step by step.

 Step 1

In the beginning, index 0 carries 8 while index 1 carries 3. Since we have to sort the array in ascending order, therefore, the value of index 0 will be replaced with the value of index 1. Now, the updated array will be: Now the value of index 1 will be compared with the value of index 2. The value of index 1 is 8 while the value of index 2 is 1 which is less than 8, so it will be swapped and the array will be modified as: Now, we will make a comparison between index 2 and index 3. The value of index 2 is 8 which is greater than the value of index 3 which is 2 so the values will be swapped: Now compare the value of index 3 with the value of index 4. At index 3 value is 8 while at index 4 value is -1 which means both these values will be swapped: Finally, the value of index 4 will be compared with the value of index 5. Again 8 is greater than 7 so, it will be replaced with 7: Now, the first iteration is complete, and “8” reaches its appropriate position. So, in the next step, the comparisons will be made till the 4th index since the value of the last index is sorted.

 Step 2:

Now, the first two indexes will be compared. The value of the 1st index is less than the value of the 0th index therefore there values will be swapped: Next, we will compare the value of the 1st index with the value of the 2nd index. Here, 3 is greater than 2 so, it will be replaced with 2: Now we will compare the value of 2nd and 3rd index i.e. 3(at 2nd index) with the value of the 3rd index which is -1. Values will be swapped again since 3 is greater than -1: The value of the 3rd index is already less than the value of the 4th index so, it will remain the same: Now the last two indexes are sorted and the values are placed properly on the 4th and 5th indexes.

 Step 3:

Now in this iteration, initially the value of the 0th index will be compared with the value of the 1st index. Here, the value of the 0th index is 1 which is already less than the value of the 1st index which is 2. So, these values will remain the same. Next, compare the next two indexes, here the value of the 1st index is greater than the value of the 2nd index therefore, their values will be swapped: The value of the 2nd index is already less than the value of the 3rd index therefore, their values will not be swapped:

 Step 4:

Compare the first two indexes. The value of the 0th index is 1, which is less than the value of the 1st index(-1), so it will be swapped: Next, we will compare the value of the 1st index with the value of the 2nd index. They are already sorted, so they will remain the same: Finally, our array is sorted in ascending order.

 Implementation of Bubble Sort

Since we understood how bubble sort works, now we will implement this logic using nested loops: functionbubbleSort(ary){ leti, j; varflag = false; for(i =0; i<ary.length; i++) { flag = false; for(j = 0; jary[j + 1]) { vartemp = ary[j] ary[j] = ary[j+1]; ary[j+1] = temp; flag = true; } } if(!flag) { break; } } console.log(ary) } varary = [8, 3, 1, 2, -1, 7]; bubbleSort(ary); In the above-given code, we created an array named ‘ary’ and assigned some data to it. Afterwards, we created a function named bubbleSort and we passed the array to it. A variable named ‘flag’ is initially assigned with a value ‘false’. This flag will be used to verify if the array is completely sorted out or not. Next, the for-loop is initialized with the 0 and it will execute until it is less than the array length. Nested for-loop is utilized to draw a comparison of the value at the current index with the value at the adjacent index, the values will be swapped only if the value of the current index is higher than the value present at its adjacent index. The value of the flag will be replaced with true if any value is swapped during iteration. Once the inner loop is done, the flag variable is checked. If the flag variable stays false, it means that the array is already sorted out and the inner loop has not changed anything. In such a case, simply break the loop. Finally, the array is passed to the bubbleSort() function. The output will be:

 Conclusion

Bubble sort is a basic sorting algorithm that swaps the side-by-side elements over and over again until they are not in proper order. In this article, we presented all the basics and essential knowledge needed to understand the concept of bubble sort. Starting with the introduction that described what bubble sort is and how it works. Then we took an example to understand the concept of bubble sort. Furthermore, we implemented the same example and discussed its working in detail.

Conditional Statements

Conditional statements are responsible to execute a piece of code depending upon some conditions. Most frequently the conditional statements are used in decision-making scenarios. In this post, we will address the conditional statements thoroughly. In JavaScript, different conditional statements are available to perform different operations. Various types of conditional statements are listed below: “if” statement is used to execute a set of statements based on some truthiness of a condition. While the “else” statement is used to execute a set of statements when the condition returns false. The “else if” statement is used to define a new condition i.e. if someone wants to check multiple conditions (more than 2 conditions) then the “else if” statement will be used.

 JavaScript if Statement

Syntax of if-statement: if (condition){// body will execute only if the condition is correct.} To understand the working of if statement, let’s consider the example that prints “well done” if marks are greater than 85: var marks, output; marks= prompt("Enter you marks");if (marks > 85) { output = "Well done"; console.log(output); } We take the input from the user using the prompt function and assign the user’s input to the variable “marks”. Next, the value stored in the “marks” is tested using the “if statement”: When you run this code a pop-up window will appear as shown in the below-given screenshot: If the value entered by the user is greater than 85 then it will show an output “Well done”: In this example, we didn’t specify anything for the false condition. So, if the user enters the false condition, let’s say the user enters 55 it wouldn’t show any output because we didn’t specify anything for false conditions. Now we will extend the above-given example with the “else” statement in order to tackle the false condition.

 JavaScript else Statement

Syntax of else statement is mentioned below: if (condition){// body will be executed only if the condition is true.}else {// else part will run in that case when the condition is not true. We will extend our program to print “well done” if marks are greater than 85 and print “better luck next time” if condition is false: var marks, output; marks= prompt("Enter your marks");if (marks > 85) { output = "Well done"; console.log(output); }else{ console.log("better luck next time");} When we run this code a pop-up window will appear asking the user to enter the marks: Now if the entered marks are greater than 85 it will show “well done” else it will show “better luck next time”. Here, we enter 56 so the output will be:

 JavaScript else if Statement

Now we will use else if to specify a new condition for our program if marks are greater than 85, print “well done” else if marks are greater than 50 but less than 85 then print “Good” else print “better luck next time”: var marks, output; marks= prompt("Enter you marks");if (marks > 85) { output = "Well done"; console.log(output); }else if (marks> 50 && marks<= 85){ console.log("Good"); } else{ console.log("better luck next time");} When we run this code a pop-up window will appear, now this program will tackle three conditions first if the user enters greater than 85 marks then it will show a message “Well done”, else if the user enters marks greater than 50 but less than or equal to 85 then it will display a message “Good” else it will show a message “better luck next time”. Here, we entered 67: The output will be:

 Conclusion

Conditional statements are commands or expressions that are used for decision-making purposes. These statements perform various actions based on the conditions. This article presents a detailed overview of conditional statements with examples. Initially, we determine the conditional statements and then we consider their types. Thereafter we took some examples and understood the conditional statements along with their types.

File handling in Node.js using Streams | Explained with Examples

Building real-life applications often require the program to be able to interact with files and file systems and building an application in the NodeJS environment is no exception. For this data interaction with files through NodeJS, there is the usage of the concept of streams. Streams in NodeJS is not a node-only concept, it was first implemented in a UNIX-based operating system. Streams are a way of reading a file bit-by-bit and passing small chunks of data to the server rather than reading a file as a whole and then passing information to the server as one big data file. This may not look like a big deal but in reality, this saves a lot of time on the server.

 Streams in NodeJS

Streams work as a queue with the help of a buffer, a buffer is a small temporary space that is used to store a chunk of data that is to be transferred. Buffer works as a queue, if you want to transfer a large amount of data from one point to another, then the buffer loads a chunk of data, and passes it onto the server, and waits for the server to respond so that it can discard that chunk of data from its queue. While it waits for the server’s response, it loads more chunks of data based on the size of the buffer set by the programmer or the application. This whole process of getting a chunk from the file, loading it into the buffer, and then parsing that chunk to the application\server is known as a Stream. In NodeJS, there are three different types of streams The read-only stream called the readable stream The write-only stream called the writable stream The read and write stream is called the duplex stream

 Reading Data from a file through streams in NodeJS

To start with the tutorial, you need to use the command in the terminal: npm init -y This will create a new node project for us along with the package.json file in our directory To read some data from a file using NodeJS, you will need a file with some text in it. Therefore, create a new text file and place some “Lorem Ipsum” text using the lorem ipsum generator. Copy this text, and place it in the text file and save the text file: As you can see, the name of the text file is “myData.txt”. Create a new javascript file in the same directory and name it “streamDemo.js” To create a read or write stream we need to use the “fs” module that comes as a built-in module of the node environment. To include the fs module in your program use the following lines of code: var fs = require("fs"); Next, we need to create a read stream from our text file (that is placed in the same directory as the streamDemo.js file) using the following line: var myReadStream = fs.createReadStream(__dirname + `/myData.txt`); Now, we can use this variable “myReadStream” to perform a task every time it receives a new chunk of data. Use to following lines of code to print the chunk onto the console every time our stream gets a new chunk: myReadStream.on("data", function (chunk) { console.log("New chunk has been accepted by the program"); console.log(chunk);}); To run this program, in the terminal type the following command: node streamDemo You will see the following output in your console: As you can see, we were able to receive and print out the data from our file, however, the data that we are getting on the console is not the same as the one we have in our file. This is because we need to set an encoding procedure in the read stream. Alter, the line of the read stream to match the following line of code: var myReadStream = fs.createReadStream(__dirname + `/myData.txt`, "UTF8"); As you can see, we have added the “UTF8” encoding to our stream. Now if we rerun using the “node streamDemo” command we get the following result on our terminal: And there you go, we are reading the correct data from the file and printing it out onto the console

 Writing data to a file through streams in NodeJS

We can write to a file using the write stream in NodeJS which also comes with the module “fs”. We will write the data we received in the previous section and write it a new file which we will writeInMe.txt To write data to a file we are going to create a new write stream using the following line of code: var myWriteStream = fs.createWriteStream(__dirname + `/writeInMe.txt`, "UTF8"); As you can notice, we have already included the “UTF8” encoding in the write stream. To write the chunk we receive from the “myData” text file to the new file we are going to use the following code: myReadStream.on("data", function (chunk) { console.log("New chunk has been accepted by the program"); myWriteStream.write(chunk); console.log("Chunk written to the new text file");}); Execute the program by using the command: node streamDemo You will get the following output: As you can see in the explorer of your code editor that a new file text was automatically created and if double click on the “writeInMe” text file you will see the following data inside that file: So, from the image above it is clear that we were able to write data to a file using Streams

 Conclusion

Streams are used to load data to\from a file by\onto the application bit-by-bit or in small chunks. We can read and write data by using streams that are included in the fs (file system) module. The file system (fs) module comes as a built-in module with NodeJS. There are three different types of streams namely: readable stream, writable stream, and the duplex stream. In this post, we implemented a simple node program that allowed us to read data from a file and write that to a different file with the help of data streams and buffers.

How to Convert Data Types | Tutorial for beginners

In JavaScript, as well as in other programming languages one data type can be converted into another data type. If we have to convert one variable to another then we can use type conversion and we can do this either implicitly or explicitly. We will discuss both types of conversions in detail with the help of some examples.

 How to Convert Data Implicitly

In implicit type conversion, JavaScript instinctively changes the data type of a variable to another data type and in this case, there is no need to convert a variable forcefully to any other data type. We will discuss the implicit way of converting data type in detail with some examples:

 Implicit Conversion of Number data type to String data type

When we add a number with a string then JavaScript Implicitly converts the number into a string prior to concatenation: let Add; Add = '50' + 50; console.log("Number Added with String : " , Add); We add a string data type value ‘50’ with a numeric value of 50, here the ‘+’ operator act as a concatenation operator: Therefore, the ‘+’ operator concatenates the string with the number and as a result, we will get ‘5050’ instead of ‘100’. This shows that JavaScript implicitly converts a number into a string:

 Implicit Conversion of String data type to Number data type

In JavaScript, if we utilize subtract, division, or multiplication sign between the two strings then as a result JavaScript will automatically convert these strings to the Number data type: let sub; sub = '50' - '50'; console.log("Strings considered as Numbers '-' operation : " , sub); let div; div = '50' / '50'; console.log("Strings considered as Numbers '/' operation : " , div); let mul; mul = '50' * '50'; console.log("Strings considered as Numbers '*' operation : " , mul); In this example, we pick two numeric strings and perform subtraction, division and multiplication operations on them: In the output, we observe that when we use the “/”, “-“, or “*” operator between two numeric strings then JavaScript consider them as a number type values and give the output accordingly: Now we consider some non-numeric strings and perform the same operations on them: let sub; sub = 'Daniel' - 'Micheal'; console.log("Strings considered as Numbers '-' operation : " , sub); let div; div = 'Daniel' / 'Micheal'; console.log("Strings considered as Numbers '/' operation : " , div); let mul; mul = 'Daniel' * 'Micheal'; console.log("Strings considered as Numbers '*' operation : " , mul); Here we try to subtract, multiply, and divide the operator with two alphabetic strings “Daniel” and “Micheal”: As a result, JavaScript responded with “NaN” (this means it’s not a Numeric value):

 Implicit Conversion of Boolean data type to Number data type

JavaScript considers ‘0’ as false and all other values as true: let BolToNum; BolToNum = 50 + true; console.log("Addition of numeric value and Boolean value True : " , BolToNum); BolToNum = 50 + false; console.log("Addition of numeric value and Boolean value False : " , BolToNum); BolToNum = '50' - true; console.log("Subtraction of Non zero value and Boolean value True : " , BolToNum); BolToNum = '50' - false; console.log("Subtraction of Non zero value and Boolean value False : " , BolToNum); If we add any numeric value other than zero with “true” then the resultant value for the Boolean “true” will always be ‘1’: From the output, it is clear that when a Boolean value “true” is added or subtracted from the number then JavaScript added or subtracted “1” from the numeric value while when Boolean value is “false” then JavaScript added or subtracted “0” from the numeric value: The value of “null” is equal to zero, when we utilize an “undefined” with a numeric or Boolean value then the resultant output will be “NaN”.

 How to Convert Data Explicitly

The term Explicit defines a manual way of converting from one data type to another, for this purpose numerous built-in functions are available. Using these functions we can convert the one data type to any other data type according to the requirements. We will discuss the explicit way of converting a data type in detail with a couple of examples.

 How to Explicitly Convert the Numeric string type to Number data type

We can convert a string into a number data type using a built-in function “Number()”: let StrToNum; StrToNum = Number('50e-5'); console.log("Converting numeric string to Number type Explicitly : " , StrToNum); In this example we convert a numeric string into a numeric data type explicitly using the “Number()” method, if we didn’t utilize the “Number” method then by default JavaScript will show a string value. The output of the above-given code will be a numeric value:

 How to Explicitly Convert the Numeric string type to Boolean data type

We will utilize the same “Number” method for the Boolean value to explicitly convert the Boolean type to the number type: let BolToNum; BolToNum = 50 + Number(true); console.log("Converting numeric string to Number type Explicitly : " , BolToNum); BolToNum = 50 + Number(false); console.log("Converting numeric string to Number type Explicitly : " , BolToNum); In this example, a numeric value is added with a boolean value, and as a result, we want a numeric value. So we utilize a built-in method “Number” with the boolean value which will convert the boolean value to a numeric value: The “Number” method will convert the boolean values “true” and “false” to the numeric values “1” and “0” respectively: The output verifies that the “Number” method explicitly converts the boolean “true” to numeric value 1 and boolean “false” to numeric value 0, therefore we get “51”. When 50 is added with a boolean “true” and it gives “50”. When boolean “false” is added with the numeric value ‘50’. JavaScript offers many more functions like “parseInt()”, “parseFloat()” and “Math.floor()” to convert a string into a number data type, we can use any of these method according to our requirement: let StrToNum; StrToNum = parseInt('50.50'); console.log("String converted to Number : " , StrToNum); StrToNum = parseFloat('50.50'); console.log("String converted to Float : " , StrToNum); StrToNum = Math.floor('50.50'); console.log("String converted to Number : " , StrToNum); “parseInt” will convert the string into integer, “parseFloat” will convert the string to float value, “Math.floor” method will convert the string value to an integer number. The output of the above-given example is:

 How to Explicitly convert a numeric data type to string data type

JavaScript offers two methods “String()” and “toString()” to convert a numeric value to a string value: let NumToStr = 50;String(NumToStr); console.log("Conversion using String method : " , NumToStr);(50).toString(); console.log("Conversion using toString method : " , NumToStr); The “String()” and “toString()” methods perform exactly the same functionality. The output of the above-given example will be:

 How to Explicitly Convert a Boolean type to String data type

We can convert a boolean value into a string value using the “string()” method or the “toString()” method: let BolToStr; BolToStr = String(true); console.log("Converting Bool to String : " , BolToStr); BolToStr = String(false); console.log("Converting Bool to String : " , BolToStr); The output of this code will be:

 How to Explicitly Convert a Number/String type to Boolean data type

We can convert any string or any numeric value into a boolean data type with the help of “Boolean()” method: let Bol; Bol = Boolean(''); console.log("empty string : " , Bol); Bol = Boolean(0); console.log("convert 0 boolean : " , Bol); Bol = Boolean(undefined); console.log("convert Undefined to boolean : " , Bol); Bol = Boolean(null); console.log("convert null to boolean : " , Bol); Bol = Boolean(NaN); console.log("convert NaN to boolean : " , Bol); If we convert a numeric value “0” to Boolean type then the result will be zero, or if we pass empty string, undefined, or null or NaN then the “Boolean” method will return zero: In all these cases the “Boolean()” method will return false: All the values except the values in above example will return “true”: Bol = Boolean(50); console.log("convert a numeric value to boolean : " , Bol); Bol = Boolean('New York City'); console.log("convert a String type value to boolean : " , Bol); We put a numeric value ‘50’, and a String “New York City” in the ‘Boolean()’ method, it will return true: For example when we put a numeric value other than zero, or a string type value, then “Boolean()” method will return true:

 Conclusion

To convert one data type into any other data type is the most frequently asked question in any programming language. In this tutorial we have learned how JavaScript converts a data type implicitly or explicitly. In this article, we have discussed how we can convert a string type to a number data type or a number to string or date type to number type or conversely number to date data type, or Boolean to number type or contrarily we can convert a number type to Boolean type.

How to Create a Node.js Module

NodeJs modules are the same as vanilla JavaScript libraries, they are a block of code that is used by some external factor (some other javascript file or application). NodeJs is a javascript runtime environment, and just like vanilla javascript libraries, there are millions of NodeJs modules available on the internet. Modules, just like Js libraries, can be of a single file or can be cultivated from a bunch of files that work together to perform a specific task or to provide certain functionality. Pre-Requisites: You need to have NodeJs environment installed and running on your machine to create a node module, for a guide on how to install NodeJS click here.

 Including a module in your project

To use a particular module you need to use the keyword “require()” with the name of that module. if the module that you want to use is not a built-in module then you can download modules from the npm library by using the following command in the terminal: npm installs <name-of-module>

 Built-in Modules

NodeJS includes a lot of built-in modules, some examples of the built-in modules are: timers string_decoder child_process crypto Https

 Creating your own NodeJs Module

You can easily create your node modules and use other files of the same project or across different applications. To get started, let’s start by heading inside a folder and creating a new node project using npm. So, type in the following lines in the terminal of your code editor: $ mkdir create_node_module This will create a new folder, now we need to head inside the folder using the following command: $ cd create_node_module Now that you are inside the folder that you created, you can start a new node project using the command: $ npm init You will see the following result on your console: Just follow with the terminal-screen guide and provide a package name, author name, etc. In the end, it is going to ask you if you are okay with the package.json file: Type yes or press enter. Create a new file and name it “myfirstmodule.js”. In this file, we are going to store information about super-cars, so we need a data structure of Car which we can create with the following lines of code: class Car { constructor(name, model) {this.name = name;this.model = model;}} Next we need a list of cars with each entry mapped on the data structure that we just created: const allCars = [new Car("McLaren", 2012),new Car("Bugatti", 2020),new Car("Ferrari", 2007),new Car("Lambo", 2008),new Car("Toyota", 1993),new Car("Mustang", 2017),]; Next up, we want a function that will randomly pick cars from our list. We will also need to export this function using the keyword “exports” so that any file that requires our module can have access to this function. Use the following lines of code: exports.getRandomCar = () => {return allCars[Math.floor(Math.random() * allCars.length)];}; Create a new file in the same folder and name it as “index js”, and type in the following line inside of that file: const cars = require("./myfirstmodule"); This line will include our module in our index.js file as well, we can now call the “getRandomCar()” function using the “cars” variable: const randomCar = cars.getRandomCar(); The last thing that is left to do is to use the name and the model of the car that was randomly chosen. We do that by using the following command lines of code: console.log( `Today's hot pick is the ${randomCar.name} of the year ${randomCar.model}` ); Now all we have to do is to run the index file by typing the following command in the terminal: node index.js You will see the following result on the console: There you have it, you created your first node module, and used it in another file using exports and require statements. If you want to go the extra mile then you can publish this module on the npm library.

 Conclusion

Node modules are the equivalent of JavaScript libraries, and that is why creating new node modules isn’t a tough job. To start, you need to set up a new project using “npm init” and then you can implement the node module in another file or application by using require and exports keywords. Currently, we only implement the usage of modules within a single machine, if you want, you can even publish your module on the npm library as well.

How to Create Drag and Drop Elements with Vanilla JavaScript and HTML

HTML and JavaScript can be combined to create amazing and eye-catching animations and effects on the webpage. There are millions of websites available on the internet, and you don’t want your website to be forgotten in the midst of these websites. One of the simplest effects that you can give to an element on a web page is the drag and drop effect. To move and place an item to any point on the webpage. In this post, we are going to show you how to make an element draggable and droppable on the webpage.

 Draggable and Droppable element with HTML and JavaScript

Create a new HTML element and inside the HTML file’s body tag, create a new div element with the following lines of code: <div id="dragElement" class="dragElement"><p>Drag and Drop me</p></div> This will create the following webpage: To style this element a little, write the following code outside of the <body> tag: <style>.dragElement {width: 100px;height: 70;background-color:lightblue;display: inline-block;align-items: center;vertical-align: bottom;} </style> By changing this style you get the following output on the webpage: For the script code, create a new script tag <script>, the javascript we will be placed inside of this script tag. For the javascript part, we are going to first create a new var that will later use the reference of the element to change its position on the webpage: var dragValue; Next, we are going to create a function named move() that we will use to move the element. The first thing we are going to do inside this move function is to get the reference of our element inside a variable with the following line of code: var element = document.getElementById("dragElement"); Not that we have our reference, we are going to set the position of this element to absolute. As we are moving the element with our choice we want to place it exactly where we want, not relative to some other element: element.style.position = "absolute"; When we click on this element, we want to pass the reference of our element to the “dragValue” variable so that we can manipulate its position: element.onmousedown = function () { dragValue = element;}; Now, that we have the reference of our element stored in the dragValue variable, we are now going to place it at the mouse’s location by using the following lines of code: document.onmousemove = function (e) { var x = e.pageX; var y = e.pageY; dragValue.style.left = x + "px"; dragValue.style.top = y + "px";}; When we release the mouse button, we want to remove the reference of our element from the “dragValue” variable: element.onmouseup = function () { dragValue = null;}; The last step is to invoke this move() function with the following line of code: move(); The complete script code will be: <script> move(); var dragValue; functionmove() { var element = document.getElementById("dragElement"); element.style.position = "absolute"; element.onmousedown = function () { dragValue = element; }; element.onmouseup = function () { dragValue = null; }; document.onmousemove = function (e) { var x = e.pageX; var y = e.pageY; dragValue.style.left = x + "px"; dragValue.style.top = y + "px"; }; }</script> Save the file and execute the HTML, and you will get the following result on your browser: And there you have it; you have made a drag and drop element in vanilla javascript

 Conclusion

One of the simplest effects that you can create using the vanilla javascript along with HTML is the draggable and droppable element on your webpage. Among the midst of millions of websites, you want your webpage to stand out. For that, the webpage needs to be super attractive and interactive. There are multiple ways of doing one particular effect or animation thanks to the ever-increasing amounts of javascript libraries. But today we focused on creating something interactive using vanilla javascript.

How to Deep Clone Objects

JavaScript is entirely based on objects, everything is an object. Arrays are objects, Strings are objects and objects are objects. When you are working with objects or arrays, sometimes there comes a need to copy or clone an array or object. There are two types of clones of objects\arrays, one of them being shallow clones and the other one being deep clones. To create deep clones in vanilla JavaScript, we need to use a combination of JSON parse() function and JSON stringify() function. In this post, we are going to discuss what are shallow clones and deep clones, how to make clones, and how to make deep clones.

 Shallow Clones vs Deep Clones

Whenever an array\object containing another array\object inside it is copied from one variable to another variable, the elements of that array\object are not copied; rather a reference pointer is copied to the new variable which points at the old variable. Such copies are known as shallow copies or shallow clones Whereas, when the elements of an array\object are copied directly (not their reference pointer) to a new variable along with the nested array\object then that copy is known as deep clones or deep copies.

 Explanation with JavaScript Code

These are advanced JavaScript concepts, that is why we will use coding examples to demonstrate the difference between shallow cloning, and deep cloning. To get started, create an array containing various elements using the following line of code: var originalArray = [true, false, 2, "Google", undefined]; Now, there are two ways of cloning this array: By using the slice method By using the spread operator To create a clone using the slice method use the following line: var clone1 = originalArray.slice(0); And to create a clone using the spread operator use the following line: var clone2 = [...originalArray]; To test if our elements were copied or not we can use the console log function to print out the original array as well as both of our clones: console.log(originalArray); console.log(clone1); console.log(clone2); We get the following output on our console: To prove these are actual clones, and not references of the original array passed inside these variables we are going to make some changes in the clones and check if these changes affect the original array or not. clone1[0] = 1; clone2[1] = "Hello"; Print all the arrays onto the console once again to examine the changes with the following lines: console.log(originalArray); console.log(clone1); console.log(clone2); You will observe the following output: As you can see, changes in the clone arrays didn’t affect the original array which means that other arrays didn’t copy the reference of the original array.

 Shallow clones verification

We have seen how to clone simple arrays, but what if we have an array or object that contains another array inside it, consider the following array: var originalArray = [["Google"]]; As you can see, we have an array inside another array, let’s try to make a clone of this array using the slice method that we have already used in the above example: var clone = originalArray.slice(0); We have made a clone of this array in the variable “clone”, print out both of these arrays using the console log function: console.log(originalArray[0]); console.log(clone[0]); You should see the following result on the console of your screen: Let’s try making some changes in the cloned array with the following line of code: clone[0].push("Maps"); This should make changes in only the “clone” array and not in the original array, but this is where things get interesting. Print out both the arrays using the console log function: console.log(originalArray[0]); console.log(clone[0]); You should see the following result on your console: You can easily observe from the image above that changes in the cloned array caused changes in the original array. This means that if our object\array contains object\arrays then the cloning passes reference to the nested objects thus creating a shallow clone.

 Deep Cloning in Vanilla JavaScript

Phew… That was a lot of stuff just to explain one concept of shallow clones but then again, these are advanced-level concepts. To make deep clones using JavaScript multiple methods are available but most of them require NodeJs. To make deep clones in vanilla JavaScript, you need to use a combination of the JSON parse() function and the JSON stringify() function. Create an array with a nested array inside it with the following line of code: var originalArray = [["Google"]]; Use a combination of JSON parse and JSON stringify() with the following line: var deepClone = JSON.parse(JSON.stringify(originalArray)); Now, that we have made our clone we need to verify it by printing it out onto the console by using the console log function: console.log(clone[0]); You will get the following result on the console: Now, let’s try changing the elements of the cloned array using the following line: deepClone[0].push("Maps"); The last thing that is left is to observe both the arrays on the console to determine whether changing the cloned array changed the original array or not: console.log(originalArray[0]); console.log(deepClone[0]); You will get the following result on your console: In the above image, you can observe that changes in the cloned array didn’t cause any change in the original array. This means that the nested arrays\objects were also copied rather than their reference being passed to the new variable, and this is why such clones are called the deep clones.

 Conclusion

Deep clones in vanilla JavaScript are made by using a combination of JSON parse() function and JSON stringify() function when parsing an object\array in a new variable. Everything is an object, and when we are trying to copy nested objects, their reference to the pointer is copied to the new variable rather than copying the elements of the nested arrays\objects. When reference of an object is passed to a new object change in the new object cause changes in the old object as well which is not very efficient. This is the reason why javascript added a way of creating deep clones.

How to Enable Linting on Save in Visual Studio Code using ESLint

In JavaScript, writing well-formatted code can be tough, so we can utilize some tools that automate that process for us. Additionally, these tools provide reusability, and consistency of the code. This tutorial will provide a detailed overview of ESLint in visual studio code., we can enable the linting on saving that automatically addresses the minor issues in our code.

 How to install ESLInt in Visual Studio Code

We can use ESLint with many text editors and IDEs, but visual studio code is the one that developers use the most. In order to install ESLint in visual studio code, we have to follow the following steps: First, we have to press the “Extensions” button in the left corner, and search for the ESLint as we did in the below-given snippet: Now press the “install” button to install the ESLint in Visual Studio Code: As we are done with ESlint installation within the visual studio code. Now we need to have a project where we can test it. Let’s initialize a project first.

 How to create a Node Project?

To create a project, use the command: Now we will use the “cd” command to access our project: Now it’s time to initialize our project, for this purpose we run the following command in our terminal: > npm init -y Now we are going to install ESLint in our project and then we will initialize it: > npm install eslint@7.32.0 To initialize the “ESLint” in our project, type the command: > npx eslint --init When we hit the “Enter” button then a sequence of questions appear one after the other: Select the second option and press the “Enter” button: Next, select the import/export and option and hit the “Enter” button: Here, select the “none of these” options to select the framework: Select the “no” option for the above-given question and hit the “Enter” button to move to the next question: Select both options and press enter, next Select “JavaScript” for the final question, When we press enter we will get a message “successfully created”. Now inside our project, we have the following files: Now we will consider an example and we will break some basic rules deliberately and we will observe how ESLint will respond when we break some rules. var string = "Hello how are you";let val= 20; console.log(val); What have we done in this example? We created two variables and didn’t utilize one of them in our project: But as we enabled ESLint in our visual studio code, it underlines the variables “string” as shown in the above snippet and shows the following error in the “problems” section: And this problem will disappear when we utilize this variable somewhere in our code: var string = "Hello how are you";let val= 20; console.log(val, string); Now have a look at the below given snipped: You will see that this time there is no such issue appearing in the problem section: For a better understanding of ESLint let’s consider another example in which we will break some rules like missing semicolons and extra spaces, and we will observe how ESLint responds to it: var string = "Hello how are you";let val= 20 console.log(val)if (val == 20){ console.log(string)} In this code, we add some extra white spaces and missed the semicolons intentionally: So, technically nothing wrong with it, as shown in the problem section. However, this is not a good coding practice to put extra spaces or missing semicolons. ESLint doesn’t show any issue because these rules are not added in ESLint. We can specify them in the following file: We will open the “.eslinrc.js” file from our project’s folder and we will add some rules: We add the first rule to tackle with semicolons and the second rule to tackle with white spaces and save the changes. Now if we miss the semicolon or we put extra spaces in our code then ESLint will highlight them in the problem section:

 How to Enable Linting on Save

We can enable linting on every save, this means whenever we save our file these problems will be fixed automatically. For this purpose, first press “CTRL+,” and select the “Workspace” settings: In the search box, search for the “Code Actions On Save” and select the “Edit in settings.json” option: Add the following code in the Setting.json file: These settings will enable the linting on save.

 Conclusion

EsLint is a package that makes lint in your project really easy, and it enforces a style guide throughout our project so that we can maintain a consistent style throughout the whole project. In this article, we described how to install the ESLint extension, then we created a project and observed how linting works on visual studio code. Next, we determine how to add rules for linting, and finally, we learn how to enable ESLint on Save.

How to fetch data from an API

When building a real-life application, the application needs to interact with APIs to send and receive data., there are many ways to interact with an API but the most common and the most basic way of interacting with an API is by using the Fetch() method from the Fetch API provided by the browser. In this post, we are going to learn how to get data from a mock API using vanilla JavaScript and the fetch API.

 The fetch() Method

This method is used to collect data from any API that responds to the request of a client in the form of JSON or XML. The syntax of the fetch method is pretty simple it takes only one mandatory argument and one optional parameter as fetch(URL, options); URL: The URL of the API to reach and ask for a response in the form of JSON or XML Options: Optional parameters that help us change the request from “get” to “post” and other variants Note: The fetch method returns a promise To use the fetch() method in your JavaScript, you need to wrap it into an async function and call this fetch() with the await keyword. With the async function, the syntax is defined as async function function_Identifier (URL) {const response = await fetch(URL); var data = await response.json();}

 Fetching Data from an API using fetch() method

To test out the fetch() method to fetch data from an API you need a dummy API or a mock API. For this purpose, we are using the dummy API provided by Req|Res with the URL https://reqres.in/api/products/3. The second thing that we need is a basic understanding of how promises work, to learn about promises you can visit this link. Next up, we need a dummy HTML page with some basic elements inside it. For this example, we used the following lines in the HTML: <center><div><p>Fetching Data from API</p></div></center> This should give us the following webpage: For the JavaScript code, the first thing we need to do is store the URL in a separate variable with the following line: const URL = "https://reqres.in/api/products/3"; Then we define an async function to get the data from the API using the URL we just stored with the following lines: async function getDataFromApi(URL) {const response = await fetch(URL); var data = await response.json(); console.log(data);} What we are doing in this code is that we are waiting for a promise from the fetch(URL) and storing that promise inside the response variable. Once we get the promise, we need to convert it into the JSON format using the response.json(). Since response.json() is also a promise that returns data, we use the keyword await. Lastly, we are printing out the data fetched from the API using the console log function. Now, all we need to do is to call this async function and pass in the URL of the API with the following line: getDataFromApi(<strong>URL</strong>); The complete code snippet is: const URL = "https://reqres.in/api/products/3"; async function getDataFromApi(URL) {const response = await fetch(URL); var data = await response.json(); console.log(data);} getDataFromApi(URL); If you run this web page and head over to the console in the browser’s developer tools, you will see the following output: That is it, you have successfully fetched data from an API using JavaScript.

 Conclusion

The fetch() method from the Fetch API can be used to fetch data from an API in vanilla JavaScript. When you are working with real-life applications you need to know how to interact with an API to send and receive data. In this post, we went over the fetch() method to send a req to a mock API and received data from that API, and then converted that data into JSON with the help of promises so that it can be used in our application.

How To Index, Split, and Manipulate Strings

In JavaScript, a string can be a single character or a collection of multiple characters and these characters can be either numbers or letters, or symbols. Each character is accessible by its index number. This article will address how to index a string, and how to split a string. Moreover, we will learn some string manipulation techniques as well.

 Indexing of a String

The index number of any string starts from 0, and each character corresponds to an index number which means the first character of any string corresponds at index 0, the second character will correspond to the 1st index and the last character let’s say the ‘nth’ character will correspond at the ‘n-1’ index number. For instance, consider the below-given string to understand how a character is indexed: Here, at index 0 we have a character “T”, at index 1 we have “H”, a blank space at index number 4, and at final index “20”, we have “Y”, which means it doesn’t matter whether it’s a blank space or an alphabet each character corresponds to an index.

 How to Check the Index of a Character

We can utilize a method “indexOf()” to check the index number of a character. The indexOf() method returns the first occurrence of a character that appears multiple times: let string = "THIS IS NEW YORK CITY"; console.log("The index of 'C' is " , string.indexOf("C")); The output will return the index where ‘C’ is placed:

 How to Access a Character

In JavaScript we can access any character with the help of square brackets “[ ]” or “charAt()” method: let string = "THIS IS NEW YORK CITY"; console.log("Searched character is ", "THIS IS NEW YORK CITY"[6]); console.log("Searched character is ", "THIS IS NEW YORK CITY".charAt(6)); In this example we access a character that is placed at index 6 using both methods: In the output we will show a character ‘S’ which is located at index 6:

 How to Split a String

JavaScript offers a very helpful “split()” method to break a string. Consider an example to understand the working of the “split()” method, in this example, we will break a string by a “space”: let string = "THIS IS NEW YORK CITY"; console.log("Break the string from whitespaces ", string.split(" ")); The whole string will be split from whitespaces: As a result, we will get an array of 5 elements: Now, we can access each element of the array with its index.

 How to Convert a String in LowerCase

JavaScript provides a built-in method to convert the whole string into lower case letters: let string = "THIS IS NEW YORK CITY"; console.log("Convert the string into Lower Case : ", string.toLowerCase()); In this code, we utilize “toLowerCase()” method which will convert each character of the string into a lower case. The resultant output will be:

 How to Convert a String in UpperCase

In JavaScript, a built-in method “toUpperCase()” is utilized to convert the string characters into Upper Case: let string = "this is new york city"; console.log("Convert the string into Upper Case : ", string.toUpperCase()); The above-given code will provide the following output:

 How to Replace a Substring

We can replace a substring of any string using “replace()” method: let string = "this is new york city"; console.log("Convert the string into Upper Case : ", string.replace("this is" , "welcome to")); In this code, we want to replace “this is” with “welcome to”, the output of the above-given code will be:

 How to concatenate two strings

In JavaScript, we can combine multiple strings with the concat() method: let string1 = "this is new york city.."; let string2 = " yes it is!!"; console.log("Combine string1 and string2 : ", string1.concat(string2)); We have two strings string1 and string2 we can combine these two using the “concat()” method as: The output will display a concatenated string:

 Conclusion:

Strings are a very well-known and commonly used data type in any computer language, and there are numerous functionalities that we can perform on them. This article provides a precise understanding of how to index, split, and manipulate the strings. We discussed the major methods to manipulate the string and to better understand all these methods we considered some examples and implemented them.

How to install and use Axios

Building a real-world application often requires interaction with APIs to send and fetch data; there are multiple ways of interacting with APIs. One of the packages that allow JavaScript as well as NodeJs projects to interact with APIs with very simple and straightforward code syntax is Axios. Axios is an HTTP client, which is used to make XMLHttpRequest from the browser as well as HTTP requests for projects created with NodeJS. It is often referred to as the isomorphic HTTP client, where isomorphic means for both NodeJs and browsers(vanilla JavaScript). Axios provides methods like get, post, and delete and automatically transforms the JSON data which is something that sets it apart from the trivial JavaScript methods like the fetch() method from the Fetch API.

 Installing Axios

As already mentioned above, Axios is present for the browser as well as the node environment, which means that it can be installed with npm and in Vanilla JavaScript using the CDN-hosted Axios script. There are multiple ways of installing Axios JavaScript in your project such as:

 Using the node package manager (npm)

Axios is available to the npm library and can be easily installed in the project by running the following command in the terminal of your code editor: $ npm install axios

 Using bower to install Axios

Bower is increasingly getting more and more famous among the masses. Bower helps install web packages just like npm. If you are working with bower, then you can install Axios by using the following lines of code: $ bower install axios

 Using a CDN hosted Axios

CDN stands for content delivery networks, these networks allow you to use JavaScript libraries hosted on their servers. Axios can be installed in your project by using one of the two CDN Axios providers, the first being “JsDelivr CDN” and the other one being the “unpkg” CDN. For JsDelivr CDN use the command in your HTML file: <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> For the unpkg CDN use the command HTML file: <script src="https://unpkg.com/axios/dist/axios.min.js"></script> With these above mentioned commands you should be able to install and use Axios in your projects.

 Using Axios

To demonstrate the usage of Axios that we have just installed by using one of the methods mentioned above in a JavaScript program, we are going to need an HTML webpage. For this post, we are going to write the following lines inside the HTML file: <center><div><h3>Users</h3><ul></ul></div></center> As you can notice in the code, we have made an unordered list which we will use to display the list of users we get from the API. This should give us the following webpage on our browser: To demonstrate the fetching of data using the Axios, we are going to be using the REQ | RES API and the URL for the API is “https://reqres.in/api/users”. The next step is to write three different functions in our JavaScript file: fetch_Users(): This will use Axios to get data from the API and send the data to appendToDOM() function appendToDOM(): This will add the user’s name to the <ul> tag after creating a new list item with the help of the create_Li function create_Li(): This will take each user’s data and create a new list item with only the name of the user placed inside it: The fetch_user() function looks like this: const fetch_Users = () => { axios.get("https://reqres.in/api/users").then((response) => { const users = response.data.data; appendToDOM(users); }) .catch((error) =>console.error(error));}; The appendToDom() function can be created with the following lines: const appendToDOM = (users) => { const ul = document.querySelector("ul"); users.map((user) => { ul.appendChild(create_Li(user)); });}; And lastly, the create_Li() function can be created using the following lines of code: constcreate_Li = (user) => {const li = document.createElement("li"); li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`;return li;}; Now that we have coded all of our functions, we only have to invoke the fetch_Users function, but for that we are going to add a button in our HTML file with the following lines of code: <button id="button">Click me to get Data</button> Now that we have our button, we can execute the fetch_Users() function upon the button press using the following code in our script file: $("#button").click(function () { fetch_Users();}); The Complete HTML Code is as: <center><div><h3>Users</h3><ul></ul><button id="button">Click me to get Data</button></div></center> The complete JavaScript code is as: $("#button").click(function () { fetch_Users();}); constcreate_Li = (user) => {const li = document.createElement("li"); li.textContent = `${user.id}: ${user.first_name} ${user.last_name}`;return li;}; constappendToDOM = (users) => {const ul = document.querySelector("ul"); users.map((user) => { ul.appendChild(create_Li(user)); });}; constfetch_Users = () => { axios .get("https://reqres.in/api/users") .then((response) => {const users = response.data.data; appendToDOM(users); }) .catch((error) =>console.error(error));}; On running this code, you will get the following result on your browser: As you can see, we are able to fetch data from the API upon button press using Axios in our javascript code.

 Conclusion

Axios is an isomorphic HTTP client that is available for both the node development environment and for the vanilla JavaScript. Axios is a strictly Promise-based library, and automatically converts the data that it fetches from the API from JSON format. To use Axios in your project, you need to either install it from the npm library or add it in your HTML file by using a CDN hosted by Axios. In this post, we learned how to install and run axios in our javascript project.

How to make HTTP requests using Axios | Explained with Examples

Axios is strictly a promise-based JavaScript library that can be included in your project by either using the node package manager (npm) or CDN-hosted Axios. It is used to make XMLHttpRequest from the browser as well as HTTP requests for projects created with NodeJS. Since it can work with both node projects and for browsers, it is often referred to as an isomorphic module. It is an HTTP client, which means we can use its GET, POST, and DELETE methods to interact with APIs

 Setting up Axios in your project

If you are working with the node package manage then you can download Axios by typing in the following command in the terminal of your code editor: $ npm install axios If you are working with vanilla JavaScript, then you can include the CDN hosted Axios in your HTML file using the following line: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> Also to test out Axios, we will be using the mock API provided by Req | Res. And the URL of the API is “https://reqres.in/api/users”. Since it is a tutorial for showing you how to work with Axios to make HTTP requests, therefore, we will not manipulate with HTML elements. We only have the following lines in the HTML webpage: <center><div id="demoID">Axios HTTP Requests</div></center>

 Get Request with Axios

To make GET requests to the API using API we use the following syntax: axios.get(URL).then(response => {}).catch(error =>()); Let’s use this syntax to make a get request to the req | res user’s API: axios.get("https://reqres.in/api/users").then((response) => { const users = response.data.data; console.log(`GET users`, users); }).catch((error) =>console.error(error)); But we want to wrap this get method in a function, So use the following lines of code: const getUsers = () => { axios .get("https://reqres.in/api/users") .then((response) => { const users = response.data.data; console.log(`GET users`, users); }) .catch((error) =>console.error(error));}; Now, all we have to do is call the function getUesrs() with the following line of code: getUsers(); By running the HTML file, you will see the following results: If we expand this entry then we will be able to see the response of the API much more clearly: We made a successful GET request using Axios and printed out the response to the console.

 Post Request with Axios

To make a post request with Axios, you need to use the following syntax: axios.post(URL).then((response) => { }).catch((error)); To make a post request to the Req|Res API, we use the following lines of code that will create a new user: const createUser = (user) => { axios .post("https://reqres.in/api/users", user) .then((response) => { const addedUser = response.data; console.log(`POST: user is added`, addedUser); }) .catch((error) =>console.error(error));}; To invoke this POST request, we need to call this function createUser(), but before we do that we need to check the API on what type of JSON does it accept for a new user creation. So, on Req|Req website we can see the following JSON format for the POST request: It takes a “name” key-value pair and a “job” key-value pair. Let’s call the createUser() function with appropriate JSON inside it: createUser({ name: "John Doe", job: "Auditor",}); Run the file and you will see the following result on your browser’s console: That is it, we were able to send a POST request to an API using Axios.

 Delete Request with Axios

To make delete requests with axios to the API you have to use the following syntax axios.delete(URL).then((response) => {}).catch((error) => ()); To make delete request to the req|res API, use the following lines of code: const deleteUser = (id) => { axios .delete(`https://reqres.in/api/users/${id}`) .then((response) => { console.log(`DELETE: user is removed`, id); }) .catch((error) =>console.error(error));}; All we have to do is to invoke the function deleteUser using the following line: deleteUser(2); Run the file and observe the result on the browser’s console: There you go, we have successfully made a DELETE request to an API using Axios.

 Conclusion

Axios is an HTTP client which can be included in your node projects by using the node package manager or in your vanilla javascript project by using the CDN-hosted Axios. Axios is used to make XMLHttpRequests to an API, and it is strictly a promise-based library. In this post, we learned how to interact with an external API using Axios and make different GET, POST and DELETE requests to the API.

How To Schedule Tasks using setTimeout() and setInterval()

JavaScript provides a couple of built-in methods for time scheduling such as “setTimeout()” method and “setInterval()” method. These methods are used for scheduling the tasks, the “setTimeout()” method executes a function only once at the scheduled time but the “setInterval()” method invokes a function repeatedly after the specified wait.

 setInterval() Method

JavaScript offers a setInterval() method that allows us to invoke a function repeatedly. It takes two parameters one for the function to invoke and the second parameter is for the time. The “setInterval()” can take additional parameters and pass them to the callback function. We will consider an example to understand the working of setInterval() method: let number = 0; let number = 0; function square() { number ++; seq = number*number; console.log("Number is equal : ", number); console.log("square of the number : ", seq);} setInterval(square, 3000); In this example, we write a code to print the square of any positive number. As we have to call the square function repeatedly, therefore, we utilize the “setInterval()” method. The code will print the square of each positive number after the delay of 3 seconds:

 How setInterval works

Initially, we created a function “square( )” and within the “square( )” function we wrote the code to print the square of any number. Afterwards, we invoke the “square( )” function using the “setInterval()” method. Now what will happen? A chain will start: Wait for 3 seconds, increment the number and print the square of that number, And again wait for 3 seconds then increment the number and print the square of that number. The “setInterval()” method will repeatedly print the square of each number and won’t.

 setTimeout() Method

In JavaScript, the “setTimeOut()” method allows us to execute any function after the specified time once. It takes two parameters one for the function to invoke and the second parameter is for the time. Let’s consider the same example and apply “setTimeOut()” method and observe the difference: let number = 0; function square(){ number ++; seq = number*number; console.log("Number is equal : ", number); console.log("square of the number : ", seq);} setTimeout(square, 3000); As a result, it will invoke the square function only once which means it will print the square of only one number:

 How setInterval works

If we invoke the “square( )” function using the “setTimeout()” method, now what will happen? When we run the code, initially, it will wait for three seconds, then increment the number and print the square of that number. But this time it wouldn’t invoke the “square()” method again because “setTimeout()” calls the function only once, and as a result, we will get the square of only one number. Note: We can’t call the function within the “setTimeout()” method or in the “setInterval()” method instead, we will write only the function’s name if we do so then these methods wouldn’t work properly, the output will be printed without any delay: setTimeout( square , 3000); //correct syntax setTimeout( square () , 3000); // incorrect syntax setInterval( square , 3000); //correct syntax setInterval( square () , 3000); // incorrect syntax In this code, we have written both correct as well as the incorrect syntax for the “setTimeout()” method and “setInterval()” method

 Conclusion

JavaScript provides some built-in methods that are utilized to run some piece of code based on a timer. These functions offer different functionalities, for example the “setTimeout()” function executes any function only once while the “setInterval()” method executes any function recursively. This article provides an overview of “SetTimeout” and “setInterval()” methods with help of some examples.

How To Run Scheduled Jobs in Node.js using node-cron

When you are running a server or an industrial-level application, you want that server to manage future jobs as well. And if you are familiar with programming, you should know that the server can’t do anything until we tell it to do something. This simply means that if you want the server to do something in the near future then you need to program it in such a way that it performs a specific task at a later time. Node packages library includes a lot of packages and modules that are used to run scheduled tasks, but the most famous and the most widely used package is the cron package which is also called the “nodecron” module. The cron offers a syntax that allows the programmer to execute a specific task at equal intervals. You can use this module or cron to schedule sending emails on a specific date and at a specific time, or you can run a task every minute To run the cron on your server and to follow this post you need to have NodeJs up and running on your local machine or on your server.

 Step 1: Set up the environment

To demonstrate the use of node-cron and to explain the syntax of cron, we are going to create a new node project and write some code that will execute a job every minute. To do this, let’s first create a new directory using the following command in the terminal: mkdir testing-nodecron We created a new directory, now to head inside that directory we need to use the following command: cd testing-nodecron The next step is to set up our package.json file and install dependencies, for that we need to call the node innit using the following lines of code: npm init -y Lastly, to install the node-cron module in our node project we use the following command in the terminal: npm install node-cron This will install our task scheduler and you will see the following result in the console:

 Step 2: Making a scheduled task job

After we have set up our environment, we can move on to using the node-cron package to write some server code that will execute a certain task after every minute. To do this we need to create a new file and we will call this file perMinuteTask.js: Inside this file, the first thing that we need to add is the node-cron library with the following line: const cron = require("node-cron"); Now, the node-cron module has a function called schedule() which takes in 2 arguments The first is the time stamp denoted by a syntax of asterisks The second one being the function that will be executed at a specific time We can use this function, to run a task at every minute using the following lines: cron.schedule('* * * * *', function() { console.log('New task every minute');}); The syntax of asterisks can be denoted as # ┌───────────── minute (0 - 59) # │ ┌───────────── hour (0 - 23) # │ │ ┌───────────── day of the month (1 - 31) # │ │ │ ┌───────────── month (1 - 12) # │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday; # │ │ │ │ │ 7 is also Sunday on some systems) # │ │ │ │ │ # │ │ │ │ │ # * * * * * Looking at the syntax, we used 5 asterisks meaning that the function will be called every minute till the end of time (metaphorically)

 Step 3: Executing the code and testing the output

The last step is to run this code and examine the output of the program. To run this code, type in the following command in the terminal: node perMinuteTask.js At first terminal may look empty like this: But after waiting for a few minutes, you will get the following result on your console: As this program has no ending condition, so if you want to close this program you need to press (Control + C) to manually stop the execution And there you go, you have successfully learned how to run scheduled tasks in NodeJs using the node-cron module

 Conclusion

Cron, in reality, is a command-line tool for UNIX operating system that helps the user to schedule a job to be executed at a later time or to run a task after a set interval of time has elapsed; You can create a simple job scheduler in NodeJs by using its node-cron module. In this post, we learned about the node-cron module and how to install\use it in our node project. We learned how to run a task every minute automatically using the node-cron module.

How to submit AJAX Forms using jQuery

AJAX stands for Asynchronous JavaScript and XML. It works by sending asynchronous requests and by doing this it permits an application to reload a part of a page without updating the entire document. This tutorial focuses on the submission of AJAX forms and will serve as a guide for anyone having problems in submitting AJAX forms. In this tutorial we will be using jQuery to submit AJAX forms. Let’s see how.

 1.Create the frontend

We will create the frontend using HTML. In the following piece of code we are creating a simple form. We created two input fileds. The first input field takes in the user name and the second input field requires the email address of the user. We have included the id values to each input field because jQuery script uses these to process the form. <!DOCTYPE html><html><head><title>How to Submit AJAX Forms using jQuery</title><script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js</a>" /></head><body><div class="form"><h1>AJAX Form</h1><form action= "process.php" method= "POST"><input type= "text" id= "name" name= "name" placeholder="Full Name" /><input type= "text" id= "email" name= "email" placeholder="email" /><button type= "submit" class= "btn">Submit Form</button></form></div></body></html>

 2.Adding jQuery logic

Now we will use jQuery logic. Without jQuery sending AJAX requests can be a bit tricky but with jQuery the task becomes a little bit easy. With jQuery AJAX methods you can easily load your data from the selected HTML elements of your web page. The following code extracts data from the input fields which are name and email. Afterwards an AJAX request is made and the response is displayed. $(document).ready(function ( ) { $("form").submit(function (event) { varformData = { name: $("#name").val(), email: $("#email").val(), }; $.ajax({ type:"POST", url: "process.php" Data: formData, dataType: "json" encode: true, }).done(function (data) { console.log(data); })

 Conclusion

Forms are a crucial part of a website and AJAX allows a user to refresh a part of a page without going through the difficulty of refreshing the entire document. An AJAX form is capable of sending and receiving information in different formats like, HTML, JSON or XML. This tutorial gives the reader a step-by-step guidance to creating and submitting an AJAX form using jQuery.

How to Use Import and Export

JavaScript offers an advanced feature named modules, using these modules we can utilize any object, class, literal, or function of one JavaScript file to any other JavaScript file. It improves the code’s reusability and reduces the loading time of the HTML file. For this purpose, the JavaScript modules provide two keywords, “import” and “export”.

 Implementation of Export

A keyword “export” is required whenever we export the data of one file to another file. Using the keyword “export” we can export anything like a variable, function, or class to any other file. What we have to do is, simply write the “export” keyword prior to that variable, function, class, or anything we want to export. The syntax to export a variable, function, and class is: //exporting a variable export var emp_name;//exporting a function export function emp(){}//exporting a class export class employee{ } Now we will figure out the working of the “export” keyword with the help of the following example, Let say we create the file with the name export.js: Consider the following example that determines how to export a variable, function, or class: export let emp_name = "Mike Smith"; export function emp(){ console.log("Employee name is Mike Smith");} export class Employee{ constructor(emp_name){ console.log("Welcome " + emp_name);}} The alternate syntax for exporting the file elements is: Export{emp_name, emp, Employee }; Using the above-given syntax we can export all elements of the file in a single statement, and while importing we will utilize the same name for variable, function, and class. For example: var emp_name = "Mike Smith"; function emp(){ console.log("Employee name is Mike Smith");}class Employee{ constructor(emp_name){ console.log("Welcome " + emp_name);}} export {emp_name, emp, Employee}; Another way of exporting is default export, it is very helpful in exporting a single element: var emp_name = "Mike Smith"; export default emp_name; This helps in importing the variable into any other class with any other name.

 Implementation of Import

In JavaScript, the keyword “import” is used whenever we import anything from a file. We have to write the “import” keyword before anything we want to import from some other file. The syntax to import a variable, function, and class is: //importing a variableimport {emp_name} from ‘./file name’//importing a functionImport {emp} from ‘./file name’//importing a classimport {employee} from ‘./file name’ We created another file with the name “import.js” and imported all the data from the file “export.js”: import {emp_name} from "./export.js" console.log(emp_name);import {emp} from "./export.js" emp();import {Employee} from "./export.js" let a = new Employee("John"); A variable, function, and a class is imported from the file “./export”: The output will verify that every element present in the “./export.js” file is imported to the “import.js” file: emp_name is variable, emp is a function, and Employee is a class created in the export.js file: import { emp_name, emp, Employee } from "./export.js"; console.log(emp_name); emp(); let a = new Employee("John"); Now here, in the above code, we import all the elements in a single statement: We will get the following output: Now we will consider another example to understand how to import a default element: import _name from "./export.js" console.log(_name); We import a default member from the file “export.js” with “_name”: In the “export.js” file the variable is created with the name “emp_name”: But we access the same variable with “_name” in the “import.js” file and get the following output: We get the same output, this means while importing any default element it is not necessary to use the same name as in the first file, instead, we can also use any different names.

 Conclusion

Import and export are new features introduced in the modules of JavaScript to improve the reusability of the code. JavaScript provides import and export keywords to utilize the code of one file to other files. In this article, we determine how to work with the module’s import and export features. To better understand the concept we consider some examples and implement them. After thoroughly studying this article, someone can analyze that while using import and export features of the module we have to use the same name for the variable, function, and class in both the files (the file from where you are exporting the data and the file in which you are importing the data). While “default” is an exceptional case where there is no such requirement, you can use any name of your choice while importing.

How to work with files using FileReader API | Explained with Examples

The File Reader API provides the file reader object which can be used to read files from your local machine and use its data on your web page. You can even use it to read a file from the client’s local machine and then transfer its data to the server. Reading a file and reading its data can be done in multiple ways, but sometimes it is best to use the object\API that is supported by almost all the web-browsers. That is why the FileReader API is one of the most used objects of vanilla JavaScript for reading the contents of a file.

 File Reader Object

To create a new file reader object you need to first call the FileReader() constructor using the “new” keyword. After that, you can start using the various functions of this object. To learn more about this constructor you can visit the official documents by the MDN by clicking here.

 File Reader methods

The file reader object comes with a lot of different methods that help us parse the data of the file that we are reading. Some of the methods are executed automatically by the browsers and are called the event handler methods, for example, the “onload()” method is automatically invoked once the file reader is done reading the content of the file. To access the methods of the file reader object you use a dot-operator “ .”. Some of the methods and variables that can be accessed by using the file reader object are:: object. result: Used to get the contents of the file that was read object.readAsText: Reads the content of the file and parses them as a text object.abort: Aborts the current read operation And much more which can be read on their official documentation’s web page.

 File reader example

To demonstrate the use of the file reader API we are going to need an HTML web page with an input field of the type=” file”, we can create this using the following line in the HTML file: <center><input type="file" /></center> This will give us the following web page: Note: We didn’t use any id or class attribute in the input field as we will be referring to our input field using the query selector. For the JavaScript code, the first thing that we are going to do is to select the input field using the query selector: const input = document.querySelector(`input[type="file"]`); Next up, we are going to add an event listener of “change” on our variable input, that will call a function to load the content of the file using the following line: input.addEventListener("change", function (e) {}, false); This function event listener will execute every time the input tag loads a file, we can access the file using the “input.file” array. To display the details of the loaded file we can use the following line: console.log(input.files[0]) We get the following output on our console: Inside the function, we are going to create our file reader object using the line: const reader = new FileReader(); The file that I want to read is a text file, so here I am going to use the method readAsText of the file reader object to parse the contents of the files as textual data using the following lines: reader.readAsText(input.files[0]); Now, we can access the contents of the file we read and parsed by using the reader.result. The onload() method is automatically called when the file reader object is done reading the file, so we can display the content of the file once it is done reading by using the following commands: reader.onload = function () { console.log(reader.result);}; The complete code snippet is: const input = document.querySelector(`input[type="file"]`); input.addEventListener("change", function (e) { console.log(input.files[0]); const reader = new FileReader(); reader.readAsText(input.files[0]); reader.onload = function () { console.log(reader.result); }; },false); Run the file and select a text file on your local machine like this: You will observe the following result on your console: And there you go, you have read the content of the file and printed them out onto the console.

 Working with an Image

To read an image and to display it onto the console you need to first read the file with the readAsDataURL using the following line: reader.readAsDataURL(input.files[0]); And to display the image on your web page you need to create a new Image variable inside the onload() function using the following lines: reader.onload = function () {const img = new Image();};}, And then inside this onload function, you are going to set the source of the image variable that we created equal to the result of the file reader object: img.src = reader.result; And last, we are going to append this image variable to the Document using the following line: document.body.appendChild(img); The complete code snippet is: const input = document.querySelector(`input[type="file"]`); input.addEventListener("change", function (e) { console.log(input.files[0]);const reader = newFileReader(); reader.readAsDataURL(input.files[0]); reader.onload = function () { constimg = new Image(); img.src = reader.result; document.body.appendChild(img); }; },false); Upon running the file, you will have the following output: And there you go, now you know how to work with the File Reader API to read files on your local machine

 Conclusion

The File reader API comes as a built-in API with vanilla JavaScript and is supported by almost all web browsers. This file reader API returns us a file reader object that we can use to read the content of the file by selecting the parsing method. In this post, we learned about the file reader API, file reader object, and how to use the file reader object to read text files as well as image files. We even displayed the image on the web browser by appending it into the document.

Introduction to the DOM

Whatever action we perform on an HTML webpage like changing an element, changing the attributes of an element, or changing the style of an element using a scripting language, is executed with the help of the DOM. This is because the scripting language cannot access the HTML element on its own, that is why it requires a middle interface that links the scripting language with the HTML element. DOM can be called the structure of the document where the document can be an HTML webpage or an XML page. In this post, we are going to know what DOM is, how to work with live DOM viewers and how to access elements with a scripting language.

 What is DOM?

DOM stands for document object model and is considered to be a standard for accessing, altering, and deleting elements from the document. This standard is set by the W3C (World Wide Web Consortium) and that is why DOM is most commonly referred to as the W3C DOM. The World Wide Web Consortium defined DOM as an interface that helps languages to interact with a document while staying language-neutral. The Document in DOM stands for a document that can be an HTML document or an XML document. The Object in DOM is used to refer to elements or nodes of the document. While the Model in the DOM refers to the structure (or tree) of the document. Also, the DOM acts like an application interface (API) for the scripting language to change elements of the HTML document The structure of the document is somewhat like a tree. It contains the parent node and child nodes.

 Working with live DOM viewers

Some websites provide us with live DOM generators, one of such live DOM viewers is provided on codepen.io. Consider,the following elements inside HTML webpage: <TABLE><ROWS><TR><TD>Google</TD><TD>Bing</TD></TR><TR><TD>John Doe, Ruski</TD><TD>California</TD></TR></ROWS></TABLE> To generate the DOM hierarchy using the javascript code on code pen, Copy and paste these HTML elements inside DOM viewer on codepen.io Below this HTML Tab on “codepen”, you’ll be able to see the DOM hierarchy like: You can clearly see the parent nodes, child nodes and siblings nodes based on their indentation in the structure

 Accessing HTML elements with JavaScript

JavaScript provides multiple methods to link the elements on an HTML webpage by interacting with the DOM. These methods are namely: getElementByID() getElementByClassName() getElementByName() getElementByTagName() getElementByTagNS() To demonstrate this, create an HTML page with the following lines: <center> <div id="demo"><p>I am a P tag in the DOM</p></div> </center> Add the link to the script file using the following line: <script type="module" src="script.js"></script> Inside the script file, add the following lines of code to change the background color of this p tag: var pTag = document.getElementById("demo"); pTag.style.backgroundColor = "yellow"; You will get the following result on the browser: There you go you have changed the style of an element using scripting language.

 Conclusion

The DOM is set as a standard by W3C (World Wide Web Consortium) as an interface for the scripting language to interact with the elements of the document (HTML or XML). The scripting language (for example javascript) cannot directly access the elements of the webpage. Therefore, it interacts with the DOM and the DOM acts like an API and performs changes in the elements of the HTML webpage. The DOM structure is like a tree, having parent nodes, child nodes and sibling nodes.

JavaScript coding Practices | Code structure and Syntax

Every language has some standards that everyone has to follow. As an example, there exist some rules to speak in English such as grammar, vocabulary, etc. The same concept applies in programming languages i.e. every programming language has a syntax to execute and run a program. In this article, we will talk about the rules that we have to follow while dealing with a JavaScript program.

 Case Sensitivity

JavaScript is a case-sensitive language, this means when dealing with any built-in property of JavaScript then deal with it carefully. To better understand this concept consider the below given example: console.log("Hello World"); Console.log("Hello World"); Both statements are the same except for the first letter of the console. Now the resultant output will verify that the console the first statement will execute successfully while the second statement will through an error: From the above output, we can analyze that JavaScript is a case-sensitive language. So, we have to follow the proper naming conventions. However, variable names and function names, there is no such restriction to follow. it is a good convention to use and follow the camel-casing naming convention i.e. varName, funcName.

 Statements

In JavaScript, a program is a collection of multiple instructions, each instruction is called a statement. This statement is made up of anything like different characters, keywords, methods, or operators. JavaScript executes each statement step by step. Let’s consider the below example to figure out how a statement works: console.log("Hello World"); In this example, there is a statement that tells the browser to log “Hello World” on the console:

 Semicolons

In JavaScript, semicolons are used as a separator, for example, we have multiple statements to execute. Then we can’t write each statement one after the other like a paragraph. We have to separate every single instruction with a semicolon. For example: var a,b,c a=5 b=6 c=10 console.log("value of a : ", a) console.log("value of b : ", b) console.log("value of c : ", c); We can’t write a program as we did in this example: In this example, we have 7 statements but we didn’t separate them so this program wouldn’t work, it will through an error: We need to separate each statement, and we can do it by separating each statement by a new line and it’s a good practice to write only one statement in each line and use semicolon after each statement, as we did in the following example: var a,b,c; a=5; b=6; c=10; console.log("value of a : ", a); console.log("value of b : ", b); console.log("value of c : ", c); Now all the seven statements are separated by a semicolon “;” and JavaScript will execute each statement one after the other: On successful execution, we will get the following output: However, if the statements are written in separate lines then JavaScript would execute perfectly fine without using semicolons at the end of the statement and throw no error.

 White Spaces

JavaScript is not sensitive about white spaces and it ignores extra spaces. Consider the following example to understand the concept of white spaces: var a , b ; a= 5 ; b= 6; console.log("value of a : ", a); console.log("value of b : ", b); In this example, we put numerous white spaces in the form of blank spaces, tabs, and newlines between the different statements: The output will confirm that JavaScript ignores the extra spaces and prints the output on the console:

 Comments

JavaScript provides a structure for the comments, we can “comment” a single line or a segment of code using JavaScript comments. For example: // console.log("Hello World"); The two forward slashes “//” comment a single line: For multiline comments use “/*” at the start and “*/” at the end: /* var a,b,c; a=5; b=6; c=10; console.log("value of a : ", a); console.log("value of b : ", b); console.log("value of c : ", c); */ The code between “/*” and “*/” will be commented:

Reserved Keyword There are a number of built-in keywords like let, const, while, for, and else. These keywords are used to perform different functionalities. We can’t change their syntax according to our requirements. For example, consider the following example: let if= 5; We can’t create a variable with the reserved keyword “if”: JavaScript wouldn’t assign a value ‘5’ to the variable “if”. Because “if” is reserved for the conditional statements.

 Conclusion

Taking care of the syntax rules and following the good conventions while dealing with a JavaScript program is a good practice that every beginner web developer should adapt to. In this article, we studied the code structure and syntax of JavaScript for good coding practices. We learned that JavaScript runs a program from top to bottom and it is not sensitive to whitespaces or line breaks. Then we learn how to comment the unnecessary instructions in a program.

jQuery Effects | Explained

jQuery (if you are not already familiar with it) is a JavaScript library that contains commonly used functionalities of a webpage wrapped in different functions. Thus providing a time-saving interface for the web developer. jQuery also provides a time-saving interface to create animations and transitional effects with close to no configuration (most functions take 2 arguments at max). jQuery contains various types of functions including selectors, events, and effects. In this post, we are going to discuss various types of effects that are provided by jQuery, their syntax along with their example

 Setting up HTML and including jQuery

To start using jQuery in your project, you need to include it inside the script tag, we are using the Google Hosted jQuery with the following line: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> After this line has been added to the HTML file, we can start writing jQuery code

 The animate() method

The animate method that is offered by jQuery is used to create very basic but yet attractive animation on your webpage. This function takes three arguments: A required parameter which is the animation A speed (optional) parameter which defines the speed of the animation A callback(optional parameter) which as the name indicates is the callback function Syntax of the animate() method The syntax is pretty straight-forward as already explained above [jQuerry_Selector $( )].animate({parameter},animation_speed,callback_function); To demonstrate this, we are going to create a button and a div in our HTML file using the following lines: <center><div>Hello! I am LinuxBot</div><button>Click me!</button></center> This will give us the following result on your browser: For the jQuery code, we are going to turn the opacity of the div down to 0.7 but we are going to do it in 2 seconds using the following lines of code: $("button").click(function () { $("div:last").animate( { opacity: "0.5", },2000 );}); As you can notice, we have wrapped the animate method in a click event method so that our animation is invoked only when we click the button. Upon pressing the button, we get the following result: As you can see, we were able to animate the opacity using the animate method.

 The show() and hide() method

These methods are used to show and hide elements of a webpage, The syntax of both of these functions is almost identical as: [jQuerry_Selector $( )].show(animation_speed,callback_function);[jQuerry_Selector $( )].hide(animation_speed,callback_function); To demonstrate this, type in the following lines in our HTML file: <center><div id="demo">I can disappear and reappear</div><button id="hide">Hide</button><button id="Show">Show</button></center> You will see the following webpage on your web-browser: As you can see, we have a div with some text inside of it along with two buttons that will use these hide and show animations respectively. For the jQuery part, use the following lines of code in your JavaScript file: $("#Show").click(function () { $("#demo").show(2000);}); $("#hide").click(function () { $("#demo").hide(2000);}); Notice: We have passed the time as 2 seconds, otherwise the change will be instant and we won’t get an animation like effect. Execute the file and click on the Hide button and you will get the following result: As you can see, we get an attractive animation, the next step is to test the show animation by clicking on the show button. So, click on the show button and you will get the following results: As you can see, we get a smooth unhide\show animation

 The slide() method:

We can get a smooth slide transition with the jQuery library as well. We get three function for the slide animation, these are namely : slideUp() slideDown() slideToggle() To demonstrate this we are going to implement a slideToggle() method, use the following lines in the HTML file: <center><div id="demo">I can disappear and reappear</div><br /><button id="toggle">Click me to toggle slide</button></center> For the jQuery code, use the following lines in the javaScript file: $("#toggle").click(function () { $("#demo").slideToggle("slow");}); You get the following result on the screen: As you can see, we have a quick and smooth slide toggle animation using jQuery. Apart from these, jQuery provides a whole bunch of other animation methods which you can try out.

 Conclusion

jQuery comes with some attractive effects and animation methods which really make a webpage stand out. jQuery is focused on making coding various methods, selectors and animation concise for the web developer. That is why some of the most commonly used animations are wrapped in different functions that can be invoked whenever the user wishes. Today, in this post, we went over how to use jQuery to implement some of the animations\effects on our webpage.

JSON Syntax | Explained

JSON is a standard for transferring data between different applications most commonly used in online servers to send and receive data to and from the client. JSON is based on JavaScript’s object syntax that is exactly why it is called the JavaScript Object Notation, however, the actual syntax of working with JSON is slightly different from the normal JavaScript. In this post, we are going to discuss the rules of JSON syntax, the different values that can be used inside the JSON and their syntax as well and the file type of JSON file. So, let’s get started:

 JSON Syntax rules

The syntax of the JSON is based on JavaScript object, however, it can be considered a subset of the JavaScript’s object’s syntax but not the same The difference comes from the rules of the syntax for JSON and these rules are as follows: The data inside the JSON can only be present as “key-value” pairs The key-value pairs are always separated by a colon Each data element or key-value pair must be separated by a comma To use objects inside the value of the key-value use curly brackets To use arrays inside the value field of the key-value pair use the square bracket Example { "Name": " John Doe", "age": 25, "job": "Auditor"}

 JSON Data | Explained

Now that we are familiar with the JSON syntax rules, let’s have a look at the JSON data. As mentioned in the rules as well, the data inside the JSON format can only be written in “key-value” pairs. These key-value pairs are often called the name-value pairs as well. Data consists of a key that is always encapsulated with double quotation marks followed by a colon “:” and then the value field of the data. Remember: the value field has its syntax which we are going to cover as well.

 Example of JSON Data

An example of JSON data is: { "city": "New York"} Another example would be: { "Team": "Lakers"}

 JSON Data Syntax VS JavaScript Object Syntax

In JSON, the key of the key-value pair can only be a string value encapsulated with double quotation marks, wherein JavaScript a string key-value can either be encapsulated with a single quotation mark or with a double quotation mark: In JSON: { "Bird": "Eagle"} In JavaScript: { 'Bird': "Eagle"} Moreover, object they key can be of any type strings, int, boolean and even an object can be a key of the data, like var demo = { Bird: "Eagle",}; Or: var demo = { Bird: "Eagle",};

 JSON Values | Acceptable Type

In the JSON syntax, the value field of the key-value pair can be one of the following data types: String Integer Null Objects Arrays Boolean String, as already mentioned above, are always encapsulated with double quotation marks, even if the string is being used inside an Array value. For the data type of Arrays, the value field is encapsulated with square brackets, For example: { "name": "John Doe", "age": 25, "Job": "Auditor", "Hobbies": ["Cricket", "Soccer", "Guitar", "Watching Netflix"]} An object in the value field is encapsulated with curly brackets. And you can even use nested arrays and objects, For example: { "name": "Bruce Wayne", "Super Power": "Super Rich", "Cars Owned": [ { "name": "Murciélago", "Model": "LP 640", "Status": "Crashed" }, { "name": "Aventador", "Model": " LP 700-4", "Status": "Seems Driveable after the accident" } ]}

 JSON | File Type

JSON data is often placed in a specific file which is known as the JSON file, this JSON file has the extension of .json”. The media type of the file is “application/json”

 Conclusion

JSON syntax is based on the object syntax of JavaScript and the main reason for this is that JSON was mapped on JavaSript’s objects. Even with the similarity of the two, there are some differences in syntax rules. In this post, we learned about JSON syntax rules and their subtle differences with the javascript syntax.

JSON.parse() Method | Explained

JSON or the JavaScript Object Notation is the most widely used data representation when it comes to transferring data over the internet (mostly between the web servers and client-side applications). Working with JSON requires the application to be able to convert the JSON string into a JSON object and vice versa. When a client-side application requests the web server, it gets a response in the form of a JSON string. To be able to use this data in our application, we need to either use various String operations to get the data from this string or we need to convert this string into a JSON object. For this conversion, JavaScript provides a method called the pare() method.

 The Parse() Method

This method is used to parse some string for an object; What is parsing? Parsing is the process of analyzing a string \ textual values against a specific syntax of either a low-level language or a high-level language. Syntax of the parse() method The syntax of the parse() method is as: const varIdentifier = JSON.parse(JSON_STRING); A JSON string is a JSON format of data with quotation marks on either end Imagine you have a JSON string that contains the information about a superhero like this: `{"name": "Bruce Wayne","Super Power": "Super Rich","Cars Owned": [ {"name": "Murciélago","Model": "LP 640","Status": "Crashed" }, {"name": "Aventador","Model": " LP 700-4","Status": "Seems Driveable after the accident" } ]}` To convert it into a JSON object, we need to parse it into the parse() method like so: var superHero = JSON.parse(`{"name": "Bruce Wayne","Super Power": "Super Rich","Cars Owned": [ {"name": "Murciélago","Model": "LP 640","Status": "Crashed" }, {"name": "Aventador","Model": " LP 700-4","Status": "Seems Driveable after the accident" } ]}`); Then we can print out the variable superHero to the console using the console log function: console.log(superHero); We get the following result on the console:

 Parsing Arrays in the parse() method

If you parse an array inside the parse method then it will return an array object, rather than a javascript or JSON object. To verify this take the following array: array = '["Google","Bing","Microsoft"]'; Pass into the parse() method with the following line of code: var demoVar = JSON.parse(array); Then you can print out the “demoVar” variable onto the console using the following: console.log(demoVar); You will get the following output on your screen: It is clear from the out that it returns an array instead of an object

 Date value in the parse() method

You cannot pass a Date value into the parse() method, however, you can define a date value as a string inside the JSON string and then use a conversion technique to change the date from a string back to a Date value. Create a new JSON string using the following lines of code: var varString = `{"idName" : "theticktock0","lastLoggedIn" : "2022-1-1"}` Parse this varString variable into the parse method using the following line: var varParsed = JSON.parse(varString); Print this variable to the console using: console.log(varParsed); You get the following output: As you can see from the output, the value of the “lastLoggedIn” is not a data value, to make it into a date value you can use the following line: varParsed.lastLoggedIn = new Date(varParsed.lastLoggedIn); Print this variable onto the console once again and you will observe the following result: As you can notice, this time around, we are getting a Date value rather than a normal string

 Conclusion

The web server usually responds to the client’s requests with a JSON string filled with data. To use this data in your application, we need to either use string operations which would make things complicated, or we can convert this JSON string into a javascript object. The parse() method is used to convert the JSON string into a javascript object. In this post, we learned details about the parse() method along with examples.

JSON.stringify() Method | Explained

JSON is a standard for transferring data across servers and clients, and it is the most famous format which is accepted by almost every modern programming language. Whenever the data needs to be transferred over the internet, it is transferred as a string value. When this string value is received by the application it is parsed into an object. Similarly, the objects are converted into JSON strings before sending them over the internet. In JavaScript, the method used to convert the JavaScript objects into the JSON string is the stringify() method, and today we are going to cover its usage and syntax along with examples.

 The Stringify() method

This method was introduced in the ES6 release of JavaScript, this method is used to convert JavaScript objects and JSON objects into JSON strings. To demonstrate this, take the following object: var superHero = { name:"Bruce Wayne","Super Power": "Super Rich","Cars Owned": [ { name:"Murciélago", Model:"LP 640", Status:"Crashed", }, { name:"Aventador", Model:" LP 700-4", Status:"Seems Driveable after the accident", }, ],}; If we print out this object onto the console using the following line: console.log(superHero); The result on the console is: From the output, it is clear that it is indeed taken as an object by our javascript application. Printing this object onto the console was important so that we can see the difference between a string output and an object output (because sometimes they confuse especially when working with code editors) To convert this into a JSON string we use the following line of code: var superHeroString = JSON.stringify(superHero); To verify this conversion, use the following line to print the variable superHeroString onto the console: console.log(superHeroString); We get the following result on the console: You can observe that this time around, we have printed a string onto the console

 The Stringify() Method | Syntax

The stringify() method takes in a javascript object, converts it into a string and then returns that string as its return value. The syntax is defined as stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string; The above syntax looks quite daunting if we simply it then the syntax becomes: stringify(object, replacer, space); From this syntax, you can see it takes 3 arguments: The object to be converted into the JSON string A replacer method (which is optional) A space parameter which is also optional

 Stringify() | The replacer and space parameter

To explain the replacer and space parameter, we first need an object that we will convert to a JSON string, you can create an object using the following lines: var person = { car: "Tesla", instrument: "Guitar", age: 25, city: "New York"} We can pass this object into the stringy method and display the result using the following line: console.log(JSON.stringify(person)); This will give us the following result: But what if we don’t want to include the “key-value” pair which has the key “age”. For that, we can write a replacer method and pass it inside the second argument of the stringify method.

 The replacer argument

This argument takes a replacer method(), the replacer() method takes 2 parameters, one is the key and the other is the value. To ignore a key-value pair, we can return an undefined value. Type the following lines of code: functionreplacer(key, value) {if (key === "age") { returnundefined; }return value;} Now, if we use this replacer method as an argument to the stringify method with the following lines of code: console.log(JSON.stringify(person, replacer)); We get the following output on our console: As you can see, the key-value pair with the key = “age” was excluded from the resulting string.

 The space argument

The space or the spacer argument puts a certain amount of space between each key-value pair. For example, if we want a space of 10 characters between each key-value pair, we can use the following line of code: console.log(JSON.stringify(person, null,10)) You will get the following result on your console: I have marked the space with a red line to make it prominent You can use a string for the space argument as well. This string will be added as a substring before each key-value pair. To demonstrate this, take the following line of code: console.log(JSON.stringify(person, null, "S")); You will get the following outcome on your console: As you can see, the argument “S” was added as a substring before each key-value pair.

 Conclusion

The JSON.stringify() method is used to convert JavaScript objects into JSON strings so that they can be transferred over the internet or in between various applications on your local machine. This method was added with the release of the ECMAv6 version of JavaScript running on the V8 JavaScript engine. In this post, we learned about the details of the stringify() method and its usage along with its examples.

Methods to access/get elements in the DOM | explained with examples

JavaScript is the most commonly used scripting language to change the elements of a webpage, truth be told, no scripting language can directly interact with the HTML elements. The scripting language interacts with the DOM (document object model) and the DOM interacts with the HTML elements because DOM is a language-neutral application interface (API). In this post, we are going to learn about different methods that we can use that will help us alter the HTML elements using the DOM interface.

 Access\ Get Methods

JavaScript provides us with 5 different methods through which we can interact with DOM to access an element on the webpage. These methods are namely: getElementById(id) getElementsByClassName(className) getElementsByTagName(tagName) querySelector(css_Selector) querySelectorAll(css_Selector)

 Usage of access\get methods

To demonstrate the use of these get\access methods we need to first set-up an HTML file and link a javascript file using the following line: <script type="module" src="script.js"></script> Now, we need to set-up elements inside our HTML file, we can do that by using the following lines: <center><div id="demoID">I have the ID "demoID"</div><br /><div class="test">I have the class "test"</div><div class="test">I also have the class "test"</div><br /><article>I have the tag "article"</article><article>I also have the tag "article"</article><br /><div id="querySelect">I have the query as "querySelect"</div><br /><div class="querySelectAll">I have the query as "querySelectAll"</div><div class="querySelectAll"> I also have the query as "querySelectAll"</div></center> As you can see, we have some <div> with id, some with classes and we have used an <article> tag as well. Executing this HTML file will give us the following output:

 Accessing an element by using its ID

The first method that we are going to test is the getElementByID(), we are going to access the element with the ID “demoID” and we are going to change its style using the following lines of code in our javascript file: var demoID = document.getElementById("demoID"); demoID.style.backgroundColor = "yellow"; After running the file we get the following output on our browser: As you can see we were able to access the element by using its ID and then change the style of the element by using javascript.

 Accessing elements using their class name

The getElementByClassName() method returns multiple elements having the same class name. We can access elements using their class name with the following line of code: var testClass = document.getElementsByClassName("test"); Since we have 2 elements with the class name “test” that is why our variable “testClass” is of the type array and if we want to change attributes of the elements inside the array we have to refer to them using their array indexes like testClass[0].style.border = "2px solid green"; testClass[1].style.border = "2px solid brown"; Upon executing we get the following output:

 Accessing elements using their Tag Name

To select elements using their tag name we use the method getElementByTagName(), in our example, to select the elements with the tag name “article” we use the following line: var tagSelect = document.getElementsByTagName("article"); Again, we have two elements with the same tag name “article” therefore we are going to manually change their attributes using their array indexes: tagSelect[0].innerHTML = `I have changed my text`; tagSelect[1].innerHTML = `I have also changed my text`; If we run the file now, we get the following output on our browser: As you can see, we have changed the text of the elements with the tag name “article”.

 Accessing an element using Query selector

We can select elements by using a query selector, to do that we use the method document.querySelector(), and if we want to select an element with a specific id, we use the “#” symbol in the query selector as var querySelect = document.querySelector("#querySelect"); After we have accessed the element we can change its border with the following line: querySelect.style.border = "1px solid red"; You will get the following result on your browser:

 Accessing an element using all query selectors

We can select all the elements with the same query using the querySelectorAll() method. Append the following line in the javascript file: const demoQueryAll = document.querySelectorAll(".querySelectAll"); To change the attributes of both the elements accessed by this querySelectorAll(), use the following lines of code: demoQueryAll.forEach((query) => { query.style.border = "1px solid green";}); You will get the following results on your browser: That is it for accessing elements using all the methods offered by JavaScript.

 Conclusion

There are 5 main methods provided by javascript that help us access\get elements of an HTML webpage with the help of the DOM interface. In this post, we learned about all 5 methods, implemented all those methods by changing the attributes of the elements that we accessed. We need the DOM interface to do all these alterations because no scripting language can directly access the HTML elements rather the DOM works as an API for the scripting language.

Methods to Search through Arrays

JavaScript offers numerous searching methods that are used to search an element in the array. The most commonly used searching methods include the filter() method, includes() method, find() method and indexOf() method. Each method has its own properties and performs different functionalities. Anyone can use these methods according to his needs.

 Implementation of filter() method

The filter() function filters the data depending upon some specific condition and returns a new array of only those elements that satisfy the applied condition. Suppose we have an array of ten elements and we want only those values that are divisible by 2: const Original_Array = [12, 25, 33, 20, 75, 2, 16, 77, 87, 100];const Filtered_Elements = Original_Array.filter(element => element%2 ==0); console.log("Array of elements divisible by 2 :", Filtered_Elements); In this example, we pass a condition to the filter function that checks whether the element’s remainder is equal to zero or not: If the remainder is equal to zero then the filter method will pick that element and put it into the filtered array. As a result, we will get a resultant array of elements that are divisible by 2: In the output, we can observe that the resultant array is reduced to 5 elements since there are only 5 elements that are divisible by 2.

 Implementation of includes() method

JavaScript offers another well-known searching method named “includes()” that takes a parameter and compares it with all the array elements consequently and if it finds the targeted value then it returns true else false. In addition to this, we can also pass another parameter to the “includes()” method that specifies from which index to start the comparison. Suppose we want to search a value ‘75’ in the array: const originalArray = [12, 25, 33, 20, 75, 2, 16, 77, 87, 100];const searchedElement = originalArray.includes(75); console.log("The searched element found in the array : ", searchedElement); In this example, we passed only one parameter to the “includes()” method: The includes() function searched for ‘75’ and it found ‘75’ at index 4, so the output will be “true” as shown below: Now let’s assume an example where we searched for the element that is present in the array. However, we restrict the includes() function to start comparison from the index 3: const originalArray = [12, 25, 33, 20, 75, 2, 16, 77, 87, 100];const searchedElement = originalArray.includes(25, 3); console.log("The searched element found in the array : ", searchedElement); So in this example, the “includes()” function starts comparing ‘25’ with other values from index 3: Although 25 is present in the array still the output will return false because we restrict the includes() function to start searching from index 3 and 25 was present at index 1:

 Implementation of find() method

The find() method is used to find an element in an array, it takes a parameter and compares it with other elements of the array. If the compared value is found in the array then it returns that value and if the compared condition satisfies more than once then it will return only the first value. This find() function will return “undefined” when the compared value isn’t found in the array. The below given example will help to understand how the find method works: const originalArray = [12, 25, 33, 20, 75, 2, 16, 77, 87, 100];const searchedElement = originalArray.find(element => element < 75); console.log("Element less than 75 : ", searchedElement); Now in this example, we searched for the elements that are less than 75. Although we searched for all those elements that are less than 75 and we can note that there are many numbers that are less than 75, the find() function doesn’t return the whole list of those elements, instead it will return only the first element.

 Implementation of indexOf() method

In JavaScript “indexOf()” function search an element in the array and returns the index of the searched element if found and if the searched element appears more than once then it returns the initial index of that element while if the searched value doesn’t found anywhere in the array then it will return -1: The below-given example will be beneficial to understand the concept of “IndexOf()” function: const originalArray = [12, 25, 33, 20, 75, 2, 16, 75, 87, 100];const searchedElement = originalArray.indexOf(75); console.log("The searched element found at index : ", searchedElement); In the above example, we searched for ‘75’ which appears twice in the array: The output will only return the first index of ‘75’.

 Conclusion

This article provides a detailed overview of searching methods. We discuss four search methods: find(), filter(), includes() and indexOf(). All these searching methods perform different functions: for example find() returns a value, includes() returns a boolean value, filter() returns a filtered list and indexOf() returns the first index of searched elements. This article helps the users to choose any of these methods according to their needs.

Mutable and Immutable data

The term mutability means changeable; the concept of mutability can be applied only to objects and arrays. Mutability’s concept can’t be applied to primitive data such as string, boolean, number, etc. While immutable data refers to primitive data whose state can’t be changed. In this post, we will understand the difference between mutable data and immutable data with the help of some examples. Before heading towards mutable or immutable data, initially, we need to clarify the concept of storing data variables. The variables are capable of storing two types of values either primitive type or reference type. Total seven primitive data types are available while there are three reference data types. The main difference between them is, in primitive data type the memory is allocated in the stack while in reference data type the memory is allocated in the heap. So, in short, the primitive data type is the base data type while the reference data type is the object made up of several features and these objects are passed as a reference.

 Mutable data

Mutable objects can be modified or revised after their creation but must remember, an object may have two references, and it’s also possible that there are two objects with the same properties. So, multiple references for one object and two objects with similar characteristics are two different things.

 Implementation of mutable data

Let’s consider an example to understand the mutability. let employee1 = { name: "Joe Clarke", age: 35, id: 123, city: 'London' }; let employee2 = employee1; let employee3 = { name: "Joe Denly", age: 25, id: 121, city: 'Birmingham'}; console.log("check Whether employee1=employee2", employee1===employee2); console.log("check Whether employee1=employee3", employee1===employee3); We created an object named “employee1” and assigned it some properties, in the second line we created a variable “employee2” and assigned it the variable “employee1” which means the “employee2” would have the same properties as the “employee1”. Afterwards, we create another variable with the name of “employee3” and we assign it some different properties. Lastly, we checked whether “employee2” and “employee3” has the same properties as “employee1” or not. Output of the above code will be: Now, let’s see what happens if we change the value of “employee1”, will it affect the properties of “employee2”? Let’s modify our code: let employee1 = { name: "Joe Clarke", age: 35, id: 123, city: 'London' }; let employee2 = employee1; employee1.name = "Dean Elgar"; console.log("updated values of employee1 : ", employee1); console.log("updated values of employee2 : ", employee2); Let’s check whether it affects the name property of employee2 or not. The output for our modified code will be: From the above-given output, we can see that changes that we make in the property of “employee1” has affected the value of “employee2” as well. This happens because “employee2” was created with the reference of “employee1”.

 Immutable data

Immutability refers to the primitive values like string, or number, etc and, we can’t modify them but we can reassign them with some new values.

 Implementation of immutable data

The below-given example will help you to understand the immutable data types. var employee1= 'Daniel'; var employee2= employee1; console.log("name of first employee : ", employee1); console.log("name of second employee : ", employee2); We created a variable and assigned a value to it. Then we created another variable and assigned it the first variable as highlighted in the below-given screenshot. Now let’s examine the output, you will see both variables show the same output: Now change the value of “employee1” and observe, will it change the value of “employee2” as well or remain the same: var employee1= 'Daniel'; var employee2= employee1; console.log("name of first employee : ", employee1); console.log("name of second employee : ", employee2); var employee1 = 'Bryn'; console.log("updated name of 1st employee : ", employee1); console.log("updated name of 2nd employee : ", employee2); Now, observe the output: The example clarifies that when we change the value of employee1, it doesn’t affect the value of the second variable which means JavaScript treats both of them as separate variables.

 Conclusion

Mutable data can be modified at any point while immutable data contradicts with the mutable data as it can’t be changed. In this post, we explained the difference between primitive data types and reference types. Then we understood the idea of mutable and immutable data, for this purpose we took some examples and implemented them. Finally, we can conclude that if we change a value of the reference variable it will mutate the original value as well, but the primitive variable doesn’t mutate.

Quick Sort

The quicksort algorithm divides the list into sub-lists then combines these sub-lists to achieve a sorted list. It utilizes the divide and conquer approach to sort the array’s elements. There are numerous algorithms available for sorting a list however quicksort is considered as one of the best among all these algorithms.

 How Quick Sort Algorithm Works

The quicksort algorithm picks an element and considers it as a pivot element; now the pivot element is reserved. Next, we will take the two pointers ‘p’ and ‘q’. The ‘p’ pointer will move from the left side to the right side and it won’t stop until it finds a greater than or equal to the pivot element. The second pointer ‘q’ will move from the right side to the left side and it will stop searching when it finds an element less than or equal to the pivot element. So, ‘p’ will sort the smaller elements at the left side and ‘q’ will sort the greater elements to the right side. Now we will understand the working of the quick sort algorithm with the help of an example: Suppose we have an array of six elements and we want to sort it in ascending order using a quicksort algorithm: In the initial step, we select ‘36’ as a pivot element (mid element): In the next step, we select our pointers, ‘p’ pointer to move from left to the right and ‘q’ pointer to move from right side to the left side: Now the value of the left pointer ‘p’ will be compared with the pivot value, as ‘35’ is less than ‘36’ move the ‘p’ pointer to the adjacent element. On the other hand, compare the value of the right pointer ‘q’ with the pivot value, ‘39’ is greater than ‘36’ so the ‘q’ pointer will move to the left adjacent element: Now, the ‘p’ pointer is pointing to ‘33’ and is compared with pivot ‘36’, the value of the pointer ‘p’ is less than the pivot value, therefore pointer ‘p’ will be shifted to the adjacent element. While the ‘q’ pointer’s value ‘32’ is less than pivot value ‘36’, so it will stop here: The left pointer’s value ‘37’ is greater than the pivot’s value ‘36’ so, it will also stop here. Now, ‘p’ stops at ‘37’ and ‘q’ stops at ‘32’. Now we will check whether the ‘p’ pointer crosses the ‘q’ pointer or not. In this case, so far ‘p’ doesn’t cross the ‘q’ pointer, so we will swap the value of pointer ‘p’ with the value of pointer ‘q’: Now ‘p’ and ‘q’ are pointing to ‘32’ and ’37’ respectively, shift the pointers one more time, now p = q(‘36’ = ‘36’): Move the pointers one more time, as the ‘p’ pointer crosses the ‘q’ pointer so here, it will stop and return the index of ‘p’ pointer. Up till now, the pivot element is in its right position and all the elements greater than the pivot element are on the right side of the pivot, and all the elements less than pivot elements are on the left side of the pivot. In this way, we will sort the whole list. Now we will implement this concept. First, the code to swap elements: function swap_elements(elements, left_Index, right_Index){ var temp = elements[left_Index]; elements[left_Index] = elements[right_Index]; elements[right_Index] = temp;} Next, the code to divide a list into sub-lists: function Sub_lists(elements, left_pointer, right_pointer) { var pivot = elements[Math.floor((right_pointer + left_pointer) / 2)], i = left_pointer, j = right_pointer; while (i <= j) { while (elements[i] pivot) { j--; } if (i 1) { index = Sub_lists(elements, left_pointer, right_pointer); if (left_pointer < index - 1) { quick_Sort(elements, left_pointer, index - 1); } if (index < right_pointer) { quick_Sort(elements, index, right_pointer); } } return elements;} We created a function that takes three parameters within the function. We divide the whole list into sub-lists and find out the left pointer and right pointer and we write the code to increment the left pointer if it’s less than the pivot element and decrement the right pointer if it’s greater than the pivot element: Now we will write the code to handle the recursive behavior of the quick sort. Since in the above step left_pointer’s index is returned and we will utilize it to divide the list into sub-lists and to apply quicksort on those sub-lists: function quick_Sort(elements, left_pointer, right_pointer) { var index; if (elements.length > 1) { index = Sub_lists(elements, left_pointer, right_pointer); if (left_pointer < index - 1) { quick_Sort(elements, left_pointer, index - 1); } if (index < right_pointer) { quick_Sort(elements, index, right_pointer); } } return elements;} The complete code snippet will go like this: var elements = [35,33,37,36,32,39]; function swap_elements(elements, left_Index, right_Index){ var temp = elements[left_Index]; elements[left_Index] = elements[right_Index]; elements[right_Index] = temp;} function Sub_lists(elements, left_pointer, right_pointer) { var pivot = elements[Math.floor((right_pointer + left_pointer) / 2)], i = left_pointer, j = right_pointer; while (i <= j) { while (elements[i] pivot) { j--; } if (i 1) { index = Sub_lists(elements, left_pointer, right_pointer); if (left_pointer < index - 1) { quick_Sort(elements, left_pointer, index - 1); } if (index < right_pointer) { quick_Sort(elements, index, right_pointer); } } return elements;} var sorted_Array = quick_Sort(elements, 0, elements.length - 1); console.log("The sorted List : ", sorted_Array); We initialized the unsorted array at the start of the program and at the end of the program we called the “quick_sort()” function to get the final sorted array: Finally, when we run this code we get the resultant output as:

 Conclusion:

Quicksort is a sorting algorithm that works on the divide and conquer philosophy and divide the problem into smaller sub-problems. And continue this process until you achieve the resultant goal. In this article, we discuss how quicksort works and implement that concept into JavaScript to sort out any array in the most efficient way.

Priority Queues

A priority queue is an extension of a simple queue data structure with elements containing a priority value, a queue is a collection of elements in which the first element to enter the queue is the first element to get out of a queue. This execution technique is known as the FIFO (First in and First Out). Consider a line of people standing outside an ATM, the person to stand first in the line will be the one to use the ATM first. The person who joins in late in the queue for the ATM will be the last one to use the ATM. So, now we know what is a basic queue, but what about the priority queue? In the priority queue, each element that enters the queue has two values, a priority value and the data. The elements which have the same priority value will be executed based on FIFO (first in and first out) but elements with higher priority than others will be executed first no matter when they were added into the queue. This is an advanced data structure topic, so we are assuming that you are familiar with how javascript works and the basic functionalities of javascript. To implement a priority queue we must first know how to implement a simple queue.

 Implementing a queue

The data structure concepts like queues, stacks, heaps, or priority queues are implemented using arrays. Let’s define a function that will define our structure: function Queue () {// Later code will be placed inside here} We know that queues are implemented with arrays, so we are going to create an array named collections Inside the function: array= []; Now, to implement the queues data structure we need to implement the following functionalities: Enqueue: To add a new element at the end of the list Dequeue: To remove the first element from the list isEmpty: To check whether the queue is empty or not Size: To return the length of the queue Front: To return the value of the first element in the list Print: To print the queue These functionalities are all easily added by using the following lines of code: functionQueue () { array= [];this.print = function() { console.log(array); };this.enqueue = function(newMem) { array.push(newMem); };this.dequeue = function() { returnarray.shift(); };this.front = function() {return array[0]; };this.size = function() { returnarray.length; };this.isEmpty = function() {return (array.length === 0); };} Now, that we have our data structure ready, we need to create an object mapped to this structure, we do that by using the line: var newQueue = new Queue(); Now, we need some elements to be placed in the queue, we do that by using the following lines: newQueue.enqueue('a'); newQueue.enqueue('b'); newQueue.enqueue('c'); To look at how our queue looks right now we can call the print function like so: newQueue.print(); We get the following output on our console: To test, if the First-in and First-out implementation is working correctly, we are going to dequeue an element from the list, and print the foremost value and then print the whole remaining queue with the following lines: newQueue.dequeue(); console.log(newQueue.front()); newQueue.print(); The complete code snippet of the Queue structure is: functionQueue() { array= [];this.print = function () { console.log(array); };this.enqueue = function (newMem) { array.push(newMem); };this.dequeue = function () { returnarray.shift(); };this.front = function () {return array[0]; };this.size = function () { returnarray.length; };this.isEmpty = function () { returnarray.length === 0; };} varnewQueue = new Queue(); newQueue.enqueue("a"); newQueue.enqueue("b"); newQueue.enqueue("c"); newQueue.print(); newQueue.dequeue(); console.log(newQueue.front()); newQueue.print(); On executing this code, we can observe the following result on the console: So, when we called the dequeue function it removed the first element from the list. After that, we checked for the foremost element in the queue which was “b”. Then we printed the queue again and it gave us the remaining queue in the correct order. This means that our queue implementation is working perfectly:

 Implementing a priority queue

We know the difference between a normal queue and a priority queue is that the elements inside the priority queue contain a priority value along with their data. This means that all the functionality of the priority queue is the same as a normal queue except for the Enqueue function. In priority queues, the enqueue function, places the higher priority element before the lower priority element. And if two or more elements have the same priority then newly added elements are placed at the later end of the queue to maintain a first-in and first-out valuation method. So, keeping that in mind we can write the new Enqueue function for the priority queue with the following lines of code: this.enqueue = function (newMem) { var array = [];// Later code will be placed inside here}; The first thing we do in the enqueue function is that if the collection is empty, then we just push the element onto the queue: if (this.isEmpty()) { array.push(newMem);} If the queue is not empty: then we are going to check the priority of the new element with the priority of every element in the queue If the priority of the new element is lower than the collection’s element.The we are going to add the new element at before that collection’s element This is because 1 means first priority whereas 2 means second priority If the priority of the new element greater in value (lower in actual priority), then we are going to move to the end of the queue and add the element there else { var added = false;for (vari = 0; i<array.length; i++) {if (newMem[1] < array[i][1]) { array.splice(i, 0, newMem); added = true;break; } }if (!added) { array.push(newMem); } } The whole enqueue function will look like this: this.enqueue = function (newMem) {if (this.isEmpty()) { array.push(newMem); } else { var added = false;for (vari = 0; i<array.length; i++) {if (newMem[1] < array[i][1]) { array.splice(i, 0, newMem); added = true;break; } }if (!added) { array.push(newMem); } } }; The rest of the priority queue functions are pretty much the same as the normal queue, with a slight change in dequeue function to display only the name and not the value of the element. The whole priority queue code snippet is as: functionPriorityQueue() { vararray = [];this.printCollection = function () { console.log(array); };this.enqueue = function (newMem) {if (this.isEmpty()) { array.push(newMem); } else { var added = false;for (vari = 0; i<array.length; i++) {if (newMem[1] <array[i][1]) { array.splice(i, 0, newMem); added = true;break; } }if (!added) { array.push(newMem); } } };this.dequeue = function () { var value = array.shift();return value[0]; };this.front = function () { returnarray[0]; };this.size = function () { returnarray.length; };this.isEmpty = function () { returnarray.length === 0; };} Time to put elements in the queue using the following lines of code: var pq = new PriorityQueue(); pq.enqueue(["Google", 2]); pq.enqueue(["Bing", 3]); pq.enqueue(["Microsoft", 1]); pq.enqueue(["Apple", 2]); pq.printCollection(); As you can see, the first priority is the “Microsoft” element with value 1. It must be at the start of the queue even if it was added at 3rd place. Now, if we call dequeue function and then the print function again the first element should be removed from the list: pq.dequeue(); pq.printCollection(); There you go, our priority queue is working perfectly.

 Conclusion

Queues are data structure concepts that work on the valuation method of first-in and first-out. Similarly, priority queues work on the valuation of first-in and first-out but with an extra value of “priority”, the element with the highest priority will be executed first no matter when they were added to the queue. In this post, we learned how to implement a simple queue and how to use that data structure to implement the working of a priority queue.

Selection Sort

The selection sort algorithm sorts the list by finding the smallest number from the unsorted list and moving it to the beginning of the list. Selection sort divides the actual list into two lists, one for sorted numbers while the second list is for the remaining unsorted numbers, initially it considers the whole list as an unsorted list. Selection sort works on a very basic philosophy that is to find the smallest number in the array and swap it to the initial position (0th index), then again find the second smallest number from the remaining unsorted array and place it to the appropriate position (first index) and so on, in this way finally, we will get a sorted array. In this article, we will discuss how selection sort works, for this purpose we will consider an example to explain each step for sorting an array using selection sort.

 How Selection Sort Works

For instance, consider the following array and sort it using selection sort:

 Step 1

Initially, we have an array of five elements, at index zero we have a value ‘9’, and we will compare it to the next index, if the value of the first index is less than the value of zero-index then next we will compare the value of index 1 to the remaining array elements. We compare ‘1’ with ‘8’, ‘1’ is less than ‘8’ so again we will compare ‘1’ with the value of the next index (3rd index), ‘1’ is less than ‘2’. It means again ‘1’ will be compared with the last index where we found a value ‘4’ which is also greater than ‘1’. So step by step we compare 1 with each element of the array and as a result, we witnessed that ‘1’ is the smallest number among all the array elements. So finally we got a sorted value for the index 0.

 Step 2:

Now after step 1 the value at index zero is sorted, so we have two sections now, at the left side a sorted array and on the right side an unsorted array: We will sort the unsorted array, so initially we will compare index one with index two, we found ‘9’ is greater than ‘8’ As ‘8’ is less than ‘9’, so from here we will compare the value of index 2 which is ‘8’ with the other array elements. Now ‘8’ is compared with ‘2’ ‘2’ is less than ‘8’ therefore in the next iteration we will compare ‘2’ with the last array elements. Compare ‘2’ with ‘4’: So, ‘2’ is the smallest element among all the unsorted array elements, so, will be swapped at the second index, resultant array after the second step will be:

 Step 3

So far we have 2 elements sorted, while three elements are unsorted. Now we will sort the remaining unsorted elements of the array. For this purpose, compare the value of index 2 with the value of index 3, so there will be no change as ‘8’ is less than ‘9’. In the next iteration, we compare ‘8’ with the value of the final index. Here ‘4’ is less than ‘8’ and ‘4’ is the last element of the array, therefore ‘4’ will be swapped with ‘8’: and the updated array will be:

 Step 4:

Now, the first three elements are sorted, compare the value of index 3 with the value of index 4, here ‘9’ is greater than ‘8’ and there is no more element left in the array for the comparison, therefore we swapped the value of forth index with the value of the third index: Finally, we get a sorted array, moreover, if someone is instructed to sort in descending order then it will be done in reverse order by finding the maximum value.

 How to implement Selection Sort

Now, we will conclude the working of selection sort in terms of each step and then we will implement the same concept. After completing the first step, we get the minimum value at the 0th index, in the second step the second smallest number is shifted to the first index. Similarly, we get a proper number at the proper index after completing the third and fourth step. We don’t need to perform sorting for the last index as we have only one element left and if all the prior elements in the array are sorted then the last element will also be sorted. Hence, we concluded that we require a total of “n-1” steps to sort an array. Now we will implement this concept of selection sort: function selection_Sort(input_Array) { let array_length = input_Array.length; for(let i = 0; i<array_length; i++) { let smallest = i; for(let j = i+1; j <array_length; j++){ if(input_Array[j] <input_Array[smallest]) { smallest=j; } } if (smallest != i) { let temp_val = input_Array[i]; input_Array[i] = input_Array[smallest]; input_Array[smallest] = temp_val; } } return input_Array;}const input_Array = [9, 1, 8, 2, 4]; selection_Sort(input_Array); console.log("Final sorted array : ",input_Array); In the initial part of the code, we utilize the “.length” property to check the length of the actual array and store it in a variable “array_length” then we iterate the loop until it reaches the “n-1” index. In the loop initially, we consider that the current index has the smallest value, therefore, we set “smallest=i” and next we use another for-loop to compare the current value to the remaining values of the array, and the loop will start from “i+1”. Next, we write the code for swapping the element once we find the smallest element in the array. Finally, we utilized the console.log() function to the output on the browser’s console:

 Conclusion

In the selection sort algorithm, we find the smallest element. We shift it to the initial index, then shift the second least element to the first index, and so on. As a result, we get an array where the sorted elements are present at the left side and the unsorted elements are present at the right side of the array. In this way, a final sorted array is constructed using selection sort. In this article, we have learned how to sort an array using selection sort. We understand the logic behind the selection sort algorithm by considering an example and explaining its working step-by-step.

Valid Data Types in JSON

JSON is the most widely used syntax\notation for transferring data over the internet and internally between various applications. JSON stands for JavaScript Object Notation. JSON is originally mapped to the Object definition of JavaScript, but it is not bound only to JavaScript. The main cause of the popularity of JSON is readability and light-weightedness. Data is represented in JSON using “key-value” pairs, the first field of this pair is the key that is used to get the value from the JSON object var JSON = {"name": "John DOe","age": 25,}; JSON supports 6 different data types which we can use when we want in the value field of the key-value pairs of the JavaScript. These 6 different data types are: Integer String Boolean Null Array object In this post, we are going to display the use of all 6 data types with their example

 Int Datatype

We can use the integer data type in the “value” part of the key-value pairs of Javascript, integer data type in JSON is used without putting any quotation marks as shown: { "Marks": 25, "totalScore": 131, "Age": 25,}

 String Data Type

To use a string data type we need to wrap it inside double quotation marks, we can use multiple escape sequences as well within the string: { "City" : "New York", "Fruit" : "Apple"}{ "Color": "orange", "model": "2016Ac2"}

 Null Datatype

If you want to give a value of null to a key-value pair, then you just write the keyword “null”, this would notify the compiler that reads this JSON that this is a nullable object: { "Parent": null, "Input": null}

 Boolean Datatype

Boolean data types only contain two values, true or false; To use boolean data type in JSON key-value pairs you simply use the keywords “true” and “false” in lowercase and with no quotation marks: { "Alive": false,}{ "isDigit": false}

 Object Datatype

JSON can be used to transfer objects as well, However, to use objects in your key-value pairs, you need to wrap the object in curly brackets “{ }”. An example of the Object Data Type in the JSON format would be: {"person": { name = "John Doe", Age = 25, Married: false, Job: "Auditor" },}

 Array Datatype

We can even use JSON to transfer arrays. To use arrays in the key-value pairs, we encapsulate the array using the square brackets “[ ] ” just like: { "person1": ["John Doe",25,"Married","Auditor"]} We can even use nested arrays in key-value pairs like: { "entry1" : [ {"id": "007"}, {"id": "008"}, {"id" : "009"}, ]} These are all the 6 data types that are supported by JSON for transferring data. Remember, JSON is mapped on the javascript’s object and Javascript object supports the following data types as well: A function Date Undefined These data types are not supported by the JSON format

 Conclusion

JSON supports 6 different data types that we can use in the “key-value” pairs to transfer them over the internet or across applications. JSON transfers data as “key-value” pairs where the first part, the “key” works like the index for reference, and the “Value” is the actual data that we want to transfer. In this post, we learned what those six data types are, how to write them in the value part of the “key-value” pairs of the JSON format.

What Are Cookies & How to Work with Them Using JavaScript

Cookies are data that are stored inside small and very manageable text files, cookies are used to tell the server about the client’s preference and other information. Cookies are mostly stored on the client’s computer, or in the client’s browser’s memory. When working with industrial-scale applications the servers cannot remember details about their client. Once the session is over with the client, the server removes all the information about the client, that is why cookies are stored on the client-side. So the next time, the client reaches out to the server with a request, a cookie is sent along with the request so that the server already knows the preferences of the client.

 What are the types of cookies?

There are three different types of cookies which are: Session cookies: These cookies are automatically deleted from your browsers once the session with the website ends First-Party Cookies: These are the cookies that are created by a specific website and can only be read by that specific website Third-Party Cookies: These are the cookies created by the advertisement running on a website that you might have visited

 What are the fields of cookies?

Generally, cookies look like name-value pairs, but they consist of 5 different fields. These fields are: Name=Value pairs: These are the cookie version of “key-value” pairs Expires: This defines when the cookie will expire from the browser, If no expiry date is specified with the cookie, then the cookie will be deleted when the browser is closed Path: The path of the website that has set the cookie in the browser, if the path is empty then deleting a specific can become a hurdle Domain: The domain name of the website that set the cookie Secure: If this field is set, then the cookie can only be read by a secure server These are all the variable fields of a cookie, apart from the name=value pairs all the other fields are optional

 How to use JavaScript to work with Cookies?

Cookies are interacted by JavaScript by using the following syntax: document.cookie = "name=value; expires: 01 Jan 2024; path=/;" To demonstrate working with cookies we are going to set up an HTML web page with the following lines inside the webpage: <center><p id="p">It’s All Cookies!!</p><button id="add">Click to add a yummy cookie!</button><button id="show">Click to show cookies</button><button id="delete">Click to delete cookie</button></center> We get the following output on our browser: Now that we have our HTML set-up we can start working on our javascript code. The first thing that we are going to implement is the functionality of the button that will add a cookie to our browser with the following lines of code: $("#add").click(function () { document.cookie = "name= Yummy Cookie!"; alert("Cookie added");}); Now, run the program and click on the button that says “Click to add a yummy cookie!”, you will get the following output: You can confirm this cookie by heading over to the developer’s console > application > cookies and finding the cookie that we just created just like shown in the image below: As you can see from the developer’s tools, we were able to successfully create our cookie. The next step is to read this cookie using JavaScript and alert the user about the cookie upon the button press, we do this by using the following lines of code: $("#show").click(function () { alert(document.cookie);}); Click on the button that says “Click to show cookies” and you will get the following result: As you can see, we can read the cookie and display it to the user. Now, we need to learn how to delete a cookie from the browser. We can delete a cookie upon button press by using the following lines of code: $("#delete").click(function () { document.cookie = "name=;expires=Thu, 01 Jan 1970 00:00:01 GMT"; alert("Cookie Deleted");}); We can delete cookies by setting their expiry date to a past date and that is exactly what we have done in the above code snippet. Now, if you press the “click to delete cookie” button you will get the following result: To verify this deletion, click on the button to show cookies once more and you will get the following result: As you can see, the alert dialogue box is not showing us any cookies, this is because we were able to delete the cookie using the delete button successfully.

 Conclusion

Cookies are small text files that are stored on the client’s computer or on the client’s browser to notify the server of the client’s preferences. There are three different types of cookies namely: Session cookies, first-party cookies, and third-party cookies. A cookie contains 5 different fields out of which only one is mandatory and the remaining 4 fields are optional. Cookies functions are done by using the document.cookie attribute. In this post, we learned how to work with cookies using javascript.

Insertion sort

Insertion sort is a simple and stable sorting algorithm that picks an element from an unsorted list and inserts it into the sorted list at the appropriate position. While the term stable algorithm refers to the scenario where two equivalent elements appear identically, then a stable algorithm holds the elements at their relative positions after the execution of the sorting algorithm is completed. Insertion sort algorithm is very helpful in those cases where we have a smaller number of elements in a list or where most of the list is already sorted and fewer elements are misplaced.

 How Insertion Sort Works

Let’s consider an example to better understand the logic behind the insertion sort. Suppose we have an unsorted array of 6 elements and we have to sort them using insertion sort: Now to sort the above array, we will iterate the array from index 1 to the last index. Initially, we assume the 0th index of the array is sorted, thereafter we will make a comparison of the current element with its prior element. If the current element is less than the prior element then we will swap their positions. First Step In the first step, we will compare index 1 with index 0, the value of the first index ‘47’ is greater than 0th index value, so there will be no change in the first step (elements wouldn’t swap): Second Step Now, in the second step, we will assume that the first two elements are sorted, so cursor will be at index 2, and we will compare index 2 with its prior elements: Since ‘25’ is smaller than ‘47’, swap ‘25’ and ‘47’. Next, ‘25’ is also compared with the 0th index value. ‘25’ is greater than ‘15’ so it wouldn’t be swapped. The array after the second step will be updated as: Third Step Here in the third step, we consider the first three values are sorted and the cursor will be at the third index. So, we will compare the third index with its prior values: At index 3, ‘55’ is compared with each element one by one but it is greater than all of its prior elements so there will be no change in the position of array elements. Fourth Step Now we are at index 4, where we have a value ‘20’ and we have to compare it with all the prior elements of the array: Since ‘20’ is less than ‘25’, ‘47’ and ‘55’ so it will be inserted at the first index, and ‘25’, ‘47’ and ‘55’ will be moved to the right side by one index (i+1 index) from their current indexes. The updated array will be: Fifth Step Now we are at index 5 where the current value is ‘10’ which is the smallest among all the array values, so it will be inserted at the 0th index. In this way, the whole array will be sorted using insertion sort: As we are done with the conceptual part of insertion sort, now we will implement this concept.

 Implementation of Insertion Sort

The code for implementing the insertion sort is as follow: function insertion_Sort(input_array, array_length) { let i, pivot_value, j; for (i = 1; i = 0 && input_array[j] > pivot_value) { input_array[j + 1] = input_array[j]; j = j - 1; } input_array[j + 1] = pivot_value; } return input_array; } let input_array = [15,47,25,55,20,10 ]; let array_length = input_array.length; insertion_Sort(input_array, array_length); console.log("final sorted array : ", input_array); In the above code, we created a function “insertion_sort” and passed it the input array and array length. Then we iterated the loop until the length of the array. Inside the loop, we selected the ‘pivot_value = input_array[i]’ as a pivot value to make a comparison of the current element with its prior elements and set “j= i-1” which represents the last element of our sorted array. Here in each iteration, the current element is assigned to the pivot value and the pivot value will be considered as the first element of the unsorted array in each step. We utilize a while loop to sort array elements, here in this loop we compare the current element with its prior elements. If the current element is less than any of the prior elements, and we found the appropriate position to insert that element in the sorted array then we insert that element at the appropriate position and move the other elements one place to the right side. And the whole phenomenon is repeated for each step until the array is sorted completely.

 Output

Finally, we call the “insertion_sort” function and print the sorted array at the console of the browser using the “console.log” method. The output of the insertion sort algorithm will be:

 Conclusion

Insertion sort is a sorting algorithm that sorts one element at a time. It inserts the element at the appropriate position one by one to create one sorted array. It provides efficient results if the number of array elements is small and most of the array elements are already sorted. In this article, we considered an example to figure out the logic of insertion sort, we discussed the working of the insertion sort algorithm with respect to each step and present the updated array after each step. And finally, once we perceived the idea behind the insertion sort then we implemented it.

Array Iteration Methods Explained with Examples

JavaScript offers some built-in iteration methods that work on each array element. The most frequently used iteration methods are forEach(), filter(), map(), reduce(), reduceRight(), every(), some(), and find(). In this article we will discuss the working of each method individually.

 JavaScript forEach() Method

In JavaScript, the forEach() method calls the given function, for every single element present in an array. The forEach method requires three parameters, one for the current element’s value, the second parameter for the current element’s index, and the final one is for the array upon which the forEach() method has to work. Consider the below-given code to understand how forEach() method works: const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"]; EmpNames.forEach(PrintNames => { console.log( "Employee name : " , PrintNames);}); In the above-given code, there is an array of five elements, and forEach() method is used with the array to print the name of each employee on the browser’s console: As a result, forEach() method will print each element on the console:

 JavaScript filter() Method

JavaScript offers another iterative method named filter() that takes a condition as a parameter and returns a new array of only those elements that fulfill the specified condition: To better understand the filter method, let’s take an example in which we want a filtered array of employees whose name starts with ‘J’: const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"];const FilteredNames = EmpNames.filter(StringIndex => { return StringIndex[0] === "J";}); console.log("Employee name : " , FilteredNames); In this example, we passed a condition to the filter() method to check the first letter of each element and return a list of elements whose first element is equal to “J”. The output will display the name of the employees that starts with “J”:

 JavaScript map() Method

The JavaScript map() method performs some functionality over the original array iteratively and produces a new array without affecting the original array. Consider an example to add the name “Wilson” with each employee name: const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"];const NewNames = EmpNames.map(AddName => { return AddName + " Wilson";}); console.log("Employees New Names : " , NewNames); We return an additional name “Wilson” with value, so it will add this name with each element of the array “EmpName”: The output of the map() method will verify that it iterates each element of array “EmpNames” and perform the same functionality over the entire array:

 JavaScript reduce() Method

The reduce() method is an array iteration method available that reduces the entire array to one value. const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"];const NewNames = EmpNames.reduce((Name1,Name2 ) => { return Name1 + " " + Name2;}); console.log("Reduced Name : " , NewNames); In the above example, we have an array with five names, using reduce() method we reduce the whole array to one name, we passed two parameters to the reduce method “Name1” and “Name2”, and we will apply some processes on them and will return them back: The output of the above code will be a single value: The reduce() method can be applied over any data type like strings, numbers, and arrays. By default, the reduce() method works from left to right, while on the contrary in cases where we want to perform functionality from right to left we can utilize the reduceRight() method.

 JavaScript every() Method

The every() method is another array iteration method, it takes a condition and tests it with every array element as a result it returns true or false. To understand how every() method works consider the following code: const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"];const EveryName = EmpNames.every(CheckName => { return CheckName[0] === "J";}); console.log("All names Starts with J : " , EveryName); In this example, we utilize every() method to test whether all the elements of the array starts with J or not: The every() method will return false because all the names in the array do not start with the letter “J”. The output would be true if all the names in the array were started with “J”:

 JavaScript some() Method

JavaScript some() method checks if some of the array elements satisfy the given condition and returns the result either true or false: const EmpNames = ["John", "Seth", "Danial", "Joe", "Micheal"];const EveryName = EmpNames.some(CheckName => { return CheckName[0] === "J";}); console.log("Some names Starts with J : " , EveryName); In this example some() method checks that either some of the employee’s name starts with J or not: In the output, it will return true because there are some employees whose names start with “J”:

 JavaScript find() Method

JavaScript offers another useful iterative method that returns only the first value which fulfills the specified condition. If more than one value fulfills the condition then instead of returning all those values, the find() method will return only the first value. Let’s understand it with an example: const EmpNames = ["John", "Seth", "Danial", "John", "Micheal"];const isFoundName = FoundName => { return [ "Micheal" , "Seth" ].includes(FoundName);}const Result= EmpNames.find(isFoundName); console.log("Employee Name : ", Result); In this example, we want to find the employees whose names are either “Micheal” or “Seth”: Here the find() method will search for these names in the array and it will print the name that comes first in the array:

 Conclusion:

Array iteration methods are built-in JavaScript methods that traverse the whole array and work on each entry of the array. In this article, we considered some essential array iteration methods and implemented them where we learned how these methods work.

Merge sort

Merge sort divides the complete list into sublists or into “n” sublists and it continues this process recursively until each sub-list has one element. Once this “divide and conquer” process is completed, it starts merging each sub-list to create a sorted list.

 How Merge Sort Works

Now we will understand the working of merge sort with the help of an example: Let’s consider another example for merge sort where we have a total of seven (odd) elements in an array and we will sort them in ascending order: [5, 7, 1, 4, 6, 3, 2] Divide the array into two sub-arrays [5, 7, 1] and [4, 6, 3, 2] Again each array will be divided into two subarrays [5], [7, 1] and [4, 6], [3, 2] Here out of four sub-arrays, one sub-array has only one element but the other three arrays still have more than one element, so we will further divide each of those arrays into two arrays. [5], [7], [1], [4], [6], [3], [2] Now the first step is complete as each array has only one item in it. Now we will compare the array elements and merge these single item arrays into pairs. [5, 7], [1, 4], [3, 6], [2] We make a comparison between the array elements of the first two arrays and the last two arrays and shift the smaller values to the left side and greater values to the right side. A comparison between the elements of the first two arrays and the second two arrays will be conducted. For instance, the first two arrays are [5,7] and [1,4]. 5 will firstly be compared to 1 and then to 4. Afterwards the second element which is 7 will undergo the same procedure and the resulting array will be [1,4,5,7]. Now we will deal with the last two arrays which are [3,6] and [2]. After comparison the array we get will be [2,3,6]. [1, 4, 5, 7] [2, 3, 6] Now we have two arrays; [1,4,5,7] and [2,3,6]. Let’s call them arrayA [1,4,5,7] and arrayB [2,3,6] respectively. First of all, the first element “1” of arrayA will be compared to the second element “2” of arrayB and the smaller number “1” will be stored in the new sorted array [1] In the next iteration, “2” will be compared with the next element “4” of arrayA. The smaller one “2” will be stored in the new sorted array. [1,2] This time, “4” of arrayA will be compared to the next element “3” of arrayB. As “3” is smaller so it will be inserted into the new sorted array. [1,2,3] This procedure will be done to each element of both arrays and once all elements are compared, the resulting array will be; [1,2,3,4,5,6,7]. [1, 2, 3, 4, 5, 6, 7]

 Merge Sort

As we have learned how merge sort works now we will code it. Create a recursive function to divide the unsorted array, we named it “merge_sort”. The recursive function always has a base case to stop the program. We pass the unsorted array to the “merge_sort” function, and inside this function, we find the middle index of the array by dividing the array’s length by 2. Moreover, we utilize the “splice()” method to split the array into sub-arrays. function merge_sort(unsortedArray) { const midle_index = unsortedArray.length / 2 if(unsortedArray.length < 2){ return unsortedArray } const leftArray = unsortedArray.splice(0, midle_index) return mergeArray(merge_sort(leftArray),merge_sort(unsortedArray)) } Now, we will discuss the code to merge the two splitting arrays. These splitting arrays are already sorted in the “merge_sort” function, and now we are merging them in the “mergeArrays” function. function mergeArrays(leftArray, rightArray) { let ary = [] while (leftArray.length && rightArray.length) { if (leftArray[0] < rightArray[0]) { ary.push(leftArray.shift()) } else { ary.push(rightArray.shift()) } } return [ ...ary, ...leftArray, ...rightArray ]} In the above-given function “leftArray” and “rightArray” are the two sorted arrays and we are merging them to obtain a single sorted array. Two methods are used in this example: the “push()” method to add the value at the end of the sorted array and the “shift()” method to delete the value which is selected from the sub-array. Lastly, the console.log() method is used to test the output. The complete code snippet would go like this: function mergeArrays(leftArray, rightArray) { let ary = [] while (leftArray.length && rightArray.length) { if (leftArray[0] < rightArray[0]) { ary.push(leftArray.shift()) } else { ary.push(rightArray.shift()) } } return [ ...ary, ...leftArray, ...rightArray ]}function merge_sort(unsortedArray) { const midle_index = unsortedArray.length / 2 if(unsortedArray.length < 2){ return unsortedArray } const leftArray = unsortedArray.splice(0, midle_index) return mergeArrays(merge_sort(leftArray),merge_sort(unsortedArray)) } unsortedArray = [5, 7, 1, 4, 6, 3, 2]; console.log(merge_sort(unsortedArray)); Output:

 Conclusion:

Merge sort divides a list into sub-lists, and it continues dividing the list until a sub-list gets a single element then it merges all the sub-lists and produces a new sorted list. In this post, we learned the concept of merge sort, then we considered some examples, and finally, we implemented them. We have also explained how the splice method, push method, and shift method works.

Scope and Hoisting of Variables | Explained with Examples

In a JavaScript program, the scope of a variable defines how far a variable can be accessed while hoisting is a phenomenon by which you can access the variables even before their initialization.

 Variables Scope

Before diving into the scope of the variable first we have to understand what is a variable and how to create a variable. A variable acts as a container that holds some data. These variables can be created using three different keywords as “var”, “let”, and “const”. In JavaScript, a variable has two kinds of scope and we will discuss each of them with some examples.

 Block Scope

Earlier JavaScript doesn’t support block scope, but after the release of ES6, it does. ES6 introduces a couple of new keywords such as let and const, these keywords offer block scope. Block scope is represented by curly braces “{}”, which determines any variable that is declared within the block scope can’t be accessed outside of it. The variables initialized within the block are known as local variables. Now we will understand the working of variables, declared inside the block scope. Variable declared with “var” keyword doesn’t support block scope, it means we can access the variable from outside the block as well. Consider the below example where the variable is declared with the “var” keyword, and observe how it works: if(true){var a = 100; console.log("variable inside the block scope : " , a);} We created a variable inside the block using the keyword “var” and assign it the value ‘100’. When we access that variable inside the block it will show the following output: Enhance the above example a little bit more and access the ‘a’ variable outside of the block: if(true){var a = 100; console.log("variable inside the block scope : " , a);} console.log("variable outside the block scope : " , a); Now observe the output: The output verifies that the keyword “var” can’t have block scope. Now create the variables with the “let” and “const” keyword, and try to access them from outside the block scope: if(true){ let a = 100;const b = 150; console.log("let inside the block scope : " , a); console.log("const inside the block scope : " , b);} console.log("let outside the block scope : " , a); console.log("const outside the block scope : " , b); Now access both the variables from inside as well as from outside the block: The output will verify that these variables are accessible inside the block scope but when we try to access them from outside the block scope then an error occurs “Uncaught ReferenceError”:

 Global Scope

Variables that can be accessible from anywhere either from outside or inside of the function/block are known as global scope variables. No matter they are created outside the function/block or within the function or block i.e. variable created inside the block with ‘var’ keyword can be accessible from anywhere code. In JavaScript, if a variable is not declared properly then by default it will be created in the global scope. Consider the following example and observe how a global variable works: var a=100; let b=120;const c=250;if (true){ console.log("global variable : ", a); console.log("global variable : ", b); console.log("global variable : ", c);} In this example, we declared the variables globally and access them in the if-statement block: The output verifies that we can access the variables anywhere in the program that are defined globally:

 Hoisting:

Hoisting refers to a phenomenon that moves the variable declarations to the top. Here we need to understand the difference between the variable declaration and variable initialization, for example, “var a”, is a variable declaration while “a= 10” is variable initialization. Now we will take an example to understand how we write the code and how JavaScript Interpret that code: var a=10; document.write(a);var b=20; JavaScript will read it as: var a;var b; a=10; document.write(a); b=20; JavaScript moves the declaration part at the top while the initialization part remains at its position. So far in all the examples, we created a variable and assigned some value to it and then we access the variable at the end. What if we try to access any variable before its initialization/declaration. Well, in that case, JavaScript shows an undefined value as it did in the following example: console.log("Access before declaration : ", a);var a = 45; In this example, we try to print the value of the variable “a”, before its declaration, then in the next statement we created the variable and assign it a value. On successful execution, we will get the following output: This happens because, even before the execution of this code JavaScript assigned an undefined value to the “var a” then it reads “console.log(a)” and then “a=45”, therefore it shows undefined instead of 45. While skipping the keyword “var” means we are not declaring a variable instead we are just initializing a variable. In this case, if we try to access a variable before its declaration we will face a RefferenceError as we did in the following example: console.log("Access before declaration : ", a); a = 45; We try to print the value of “a” on the console before its declaration and then in the next statement we assign a value to the variable ‘a’ without using the keyword “var”: We get the following output:

 Conclusion

In JavaScript, the scope of the variable determines where you can access a variable in the code while hoisting of the variables refers to the concept of invoking the declarations of variables to the top of the program. This article provides the to-the-point examples to understand the concept of scope and hoisting of variable.

Singletons

Singleton refers to an object’s instance that can be instantiated only once. A singleton assures that a class can’t have more than one instance instead it has exactly one instance and has global scope. Singletons are global to the entire application so sometimes it can create difficulties as the entire application is relying on them. Now, we will discuss the syntax of singleton’s class, and the singleton’s function one by one. Also, we will discuss how to access their instances in detail.

 Singleton method

There are many methods that can be used to declare a singleton, a very basic way of declaring a singleton is as: var SingletonExample = { fname: 'joe', lname: 'clarke', simpleMethod: function () { return this.fname + ' ' + this.lname; }, }; console.log("simpleMethod : ",SingletonExample.simplemethod()); The output of this code will be:

 Singleton class

Implementing a singleton class is not very complex, the basic syntax of singleton class will be: let check_instance=null;class employee { constructor(id, name, city, designation) { if (!check_instance) { this.id=id; this.name=name; this.city=city; this.designation=designation; check_instance=this; } else { return check_instance;}}}const emp1 = new employee(1, 'Roman', 'Paris', 'Manager'); console.log("First employee : ",emp1); Here, we created a class named employee and a variable named check_instance with a null value. Inside the class, we use if-statement to check if the instance is null or not and if the instance is null then if-statement will be executed else it would simply return the ‘check_instance’.

 Output:

Now, create another instance and check what will happen when we create two instances of a singleton class. For this purpose simply extend the above code a little bit and create another instance of the class and assign some properties to it: let check_instance=null;class employee { constructor(id, name, city, designation) { if (!check_instance) { this.id=id; this.name=name; this.city=city; this.designation=designation; check_instance=this; } else { return check_instance;}}}const emp1 = new employee(1, 'Roman', 'Paris', 'Manager');const emp2 = new employee(2, 'Seth', ' New York', 'Director'); console.log("First employee : ",emp1); console.log("Second employee : ",emp2); Now implement the above code and observe whether a new employee is created or not:

  Output:

The output will verify that it didn’t create the second instance instead it returns the same instance again:

 Conclusion

Singletons are one of the easiest design patterns to understand. Singleton patterns are the way of creating a single object that can be shared among a number of different resources throughout the application without recreating those objects. If someone calls the constructor of a class it will return the same instance again and again.

Unary Operators | Explained for beginners

JavaScript supports numerous unary operators, these operators are very basic operators as they take only a single operand. The unary operator appears either prior to any value or subsequent to the value. A unary operator cannot be overridden.

 How to use Unary Plus Operator

JavaScript offers a Unary Plus (+) operator that is used to convert an operand to a numeric value. For example, we have a string value: let x = '50'; console.log("value of x : " , x); console.log("type of x is : " , typeof(x)); x =+x; console.log("value of x : " , x); console.log("type of x is : " , typeof(x)); We print the value of x and type of x, initially, it will show a value of x ‘50’ and type of operand as “String”, then we implement unary plus operator and we checked the type of the operand: The output verifies that implementing the unary plus operator converted the string to a numeric value:

 How to use Unary minus Operator

JavaScript Unary minus is also a well-known operator that converts an operand to a negative numeric value. We consider the same example and implement the unary minus operator on it: let x = '50'; console.log("value of x : " , x); console.log("type of x is : " , typeof(x)); x =-x; console.log("value of x : " , x); console.log("type of x is : " , typeof(x)); This time it will convert the ‘50’ into ‘-50’: We can also implement the unary plus and unary minus operators on Boolean values.

 How to use the Increment operator

The increment operator increments the value by 1 and returns the incremented value. The “++” operator can be utilized either in prefix style or in a postfix style. In prefix increment, the operator (++) comes before the operand (any value) while in the postfix increment the operator (++) comes after the operand (any value): let x = 50; console.log("value of x : " , x); let y = ++x; console.log("value of x : " , y); let a=50; console.log("value of a : " , a); let b = a++; console.log("value of a : " , a); console.log("value of b : " , b); In this example we assign ‘50’ to a variable “x” then we create another variable “y” and assigned it “prefix increment” value of “x”, then we create another variable “a” and assign it “50” while we assign “postfix increment” value of a to a new variable b: In the output, you will see that the prefix increment will increment the value of x by ‘1’ and “y” will display an incremented value of “x”, while the postfix will show the same value for both ‘a’ and ‘b’ which means although postfix increments the value of a but it will return the value before increment:

 How to use Decrement operator

The Decrement operator “–” decrements the value by 1 from the value of the operand. The “–” operator can be utilized either in prefix style or in a postfix style: let x = 50; console.log("value of x : " , x); let y = --x; console.log("value of x : " , y); let a=50; console.log("value of a : " , a); let b = a--; console.log("value of a : " , a); console.log("value of b : " , b); The decrement operator will return a decremented value for the variable ‘y’ while it will show the same output for variable ‘a’ and ‘b’, because variable ‘b’ is assigned with the postfix decrement of ‘a’ which will decrement the value of ‘a’ by 1 but still ‘b’ will return the “before decremented” value: The output of the above-given program will be:

 How to use Logical not operator

JavaScript provides another unary operator named logical not represented by “!”. Logical not invert the true value to false and false value to true: let x = true; let y = false; console.log("value of x is equal to value of y : " , (x = !y)); The above code will invert the value of ‘y’ from false to true and as a result, the value of variable ‘x’(true) will be equal to ‘!y’(true) and it will return true:

 Conclusion:

Unary operators play a very crucial role in any programming language. They work on a single operand and perform some operations on the operand depending upon the operator. In this tutorial, we address a couple of major unary operators with some examples. We have seen how unary +, unary -, increment, decrement, and logical operator works and implement each of them.

Working with Strings | explained with examples

Strings are nothing but a collection of characters, letters, numbers, or symbols., strings are primitive and immutable in nature that determines when someone implements some functionalities on a specific string then as a result it wouldn’t affect the original string instead it will create a new string.

 How to Create a String

While working with strings, the first question that comes to our minds is how to create a string? Well, we have two answers to this question, we have to understand first what kind of string we are going to create? JavaScript offers two kinds of strings: a simple “string”, “Template literals” (introduced in ES6). We will consider some examples to understand both these concepts: While creating a simple string we will enclose all the characters in a single quote ‘’ or a double quote “” as we did in the below-given example: "hello this is our first-string written in double quotes";'hello this is our second-string written in the single quote'; So far what we have done is, just surround the sequence of letters with the double quotes, and next with the single quote, we didn’t assign a string to any variable or a literal, etc. Now we can get the output of these strings in many ways, for instance, we can print the output on the browser’s console as: console.log("hello this is our first-string written in double-quotes"); console.log('hello this is our second-string written in the single quote'); Now we will get our output on the console as: While we can also get the output on our document as: document.write("hello this is our first-string written in double-quotes"); We will get the following output when we utilize “document.write()”: Another way of printing our string is the “alert” method: alert("hello this is our first-string written in double-quotes"); In this case, a pop-up window will appear and we will get our output on that window: Now we will discuss the second method “template literals” to create a string.

 Template Literals

The “template literals” perform the same as the single quote and the double-quote did, but with some additional functionalities. The template literal strings are surrounded by “back-ticks” “. We will discuss “template literals” in detail in the latter part of this article “how to concatenate strings”.

 How to Assign a String to a variable

In JavaScript, we can create a variable in three ways either with the keyword “var”, “let”, or with the keyword “const”. So, consider the below given example to understand how we can assign a string to a variable: const string1 = "string assigned to a const variable"; let string2 = "string assigned to a let variable";var string3 = "string assigned to a var variable"; We created three variables with three different keywords and we assigned a string to each of them as: We will use the console.log() method to print the output of these strings: So we will get the following output on our console:

  How to Concatenate the Strings

Concatenate means combining the multiple strings, we can concatenate multiple strings using the concatenation operator “+”: const string1 = "Daniel"; let string2 = "Bryn"; console.log("Employee Name : ", string1 + " " + string2); We created two strings and assign them to two different variables then in the console.log function we concatenated both the variables with the “+” operator. In the above-given, we combine two strings and add a “white space” between them. When we execute the code we get the following output: We can concatenate the strings directly without assigning their values to the variables, same as we did in the below example: console.log("Name : ", 'Michael'+ " " + 'Clarke'); In this example, we combine two strings, and among them a white space: And we get the following output on successful execution: Till now we worked on the strings with a single quote or strings enclosed in double-quotes. Now we will consider an example to understand how back-tick works: let First_name = "Daniel"; let Full_name = `Joe ${First_name}` ; console.log("Name : ", Full_name); In this example, we combine “First_name” with “Joe” using (`), and prints the output on the console: We will get the following output for the above code:

 How to Escape Special Characters

As we have seen in the above examples that single quotes and double quotes are utilized to signify the strings. So a question that grabs everyone’s attention is how to deal with apostrophes or some special characters within the strings? For example: let str = 'I'm a string!'; console.log(str); So in this example when we try to write I’m in a string then it wouldn’t work properly: As in the above snippet, we see that Visual Studio Code is showing an error, so if still, we try to run this code then we will get the following output: Therefore to tackle such special cases JavaScript provides some special characters like backslash ‘\’, tab ‘\t’ etc. We will take an example where we will add ‘\’ in the string: let str = 'I\'m a string!'; console.log("The String : " , str); The ‘\’ will escape the single quote as: And we will get the resultant output for the string as:

 How to Access a Character from a String

We can access a specific character of a string using array-brackets ‘[]’: let string = "hello this is our first-string written in double-quotes"; console.log("Accessed Character : ", string[8]); We write “string[8]” in the console method which determines that access the ‘8th’ character of the string and prints it on the console: Upon successful execution, we will get the 8th character of the string which is “i”:

 Conclusion

Strings are primitive and immutable datatypes and this article provides a complete overview of string’s working with the help of examples. After reading this article you will be able to answer the questions like how to create a string, how to display a string, how to assign a string to a variable, how to integrate/concatenate a string, how to escape a special character while working with strings, and how to access a single character of a string.

How to Get Started with MERN Stack

MERN Stack is a set of dependable and powerful technologies that can be utilized for developing scalable web applications. This web application comprises a front-end, back-end, and database for storing the data. It is a full-stack JavaScript framework used to build user-friendly websites and applications. To get started with the MERN Stack, we need to do the following thFirstirstly, set up the Node server, create a MongoDB database, and establish a connection with the Node server. The third and the most important step is to build the front-end React.js application. This write-up will show you how to perform all of these operations. Before moving ahead, let’s discuss the mentioned components of the MERN Stack.

 Components of MERN Stack

js is considered the top tier in the MERN stack development. It is a declarative JavaScript framework used to develop dynamic client-side applications. It also permits you to create complex interfaces by connecting the components of your data from the backend server and then rendering them as HTML. React also excels at handling data-driven and stateful interfaces with minimal code and other functionalities such as error-handling, lists, forms, events, which you expect from a modern web framework. If you want to develop an application based on MERN Stack that saves any form of the data such as events, comments, user profiles, content, and uploads, you will need a simple database to use with the front-end and back-end. This is the situation where MongoDB comes into play. In the React.js front end, the created JSON documents are sent to the Express.js and the Node.js server, processing them and storing them in the MongoDB database. In MERN stack development, the tier which is present in between the MongoDB database and the React.js front-end is the “js”. It can be described as a minimalist, unopinionated, and fast Web framework for Node.js. Express.js framework operates the Node.js server inside it. You can connect to the Express.js functions from your application front-end by sending the POSTs, GETs, or HTTP requests. These specified functions are then utilized to change or access the MongoDB data via Promises or callbacks. Express.js also offers powerful models for handling HTTP responses, requests, and URL routing. Now, let’s get started with the MERN Stack!

 How to set up the Node server in MERN Stack Development

To set up the Node server in MERN Stack development, the first thing you have to do is to download Node.js on your system through its official website: Next, use the downloaded file to complete the installation of Node.js and after completing the specified operation, execute the below-given in your Command Prompt: > node -v The above-given “node” command with the “-v” option will print out the current version of the “Node.js” which is installed on your system: After installing Node.js, we will move ahead towards the procedure of development of the server. For this purpose, firstly, we will create a base folder and then install all of the required packages or dependencies for the Node server development. For the specified operation, you can use also Command Prompt. However, we will utilize the “Visual Studio Code” terminal which will also make it easy to work in the Node Server files. In the next step, we will open up our base folder by using the “Open Folder” option of the “File” menu: We have selected the “Employee-mern-project” folder for storing the files related to the Node server of the MERN stack: Now, press “CTRL+SHIFT+`” to open up a new terminal window in the Visual Studio code. You can also utilize the “Terminal” menu for this purpose: In the next step, we will create a “backend” folder inside of our “Employee-mern-project” root or base folder. To do the same, you can execute the below-given “mkdir” command in the opened terminal: > mkdir backend After doing so, we will move into the newly created “backend” folder to add the server related file and packages in it: > cd backend Inside of the “backend” folder, we will now create a “package.json” file. The package.json file is the core element of a Node server in the MERN stack development. It comprises the metadata of your MERN stack project and also defines the functional attributes that can be then utilized by the npm for executing scripts and installing dependencies. To create a new package.json file for your Node server, type out the following command: > npm init -y

 How to install dependencies for Node server in MERN Stack Development

This section will demonstrate the procedure of installing essential dependencies such as “express”, “cors”, “mongoose”, and “dotenv” for your Node server in the MERN Stack Development. The node package manager or “npm” can be used for installing the specified dependencies in the following way: > npm install express cors mongoose dotenv Here: “express” is added to install “Express” which is a lightweight web framework for Node.js. It also has the capability to support many middlewares which assist in making the code easier and shorter to write. “cors” is an acronym for Cross-Origin Resource Sharing. This package permits AJAX requests to access the resources from the remote hosts. “mongoose” is added to install the “mongoose” package. The mongoose package helps the Node server to interact with MongoDB in MERN stack development. Lastly, the “dotenv” package will load the environment variables from the “.env” to the “process.env” file. It also manages the database credentials in a collaborative environment. For our Node server, another package that we are going to install is “nodemon”. It automatically restarts the node application when you made some changes in the file while developing the Node.js based application: > sudo npm install -g nodemon

 How to run the Node server in MERN Stack Development

Till this point, we have installed Node.js and the required packages and dependencies. Now it’s time to create and run the backend Node.js server. To do so, click on the “backend” folder, and from the drop-down menu, select the “New File” option: Here, you can a new “server.js” JavaScript file is added in the backend folder: Now, in the “server.js” file, we will create an “express” server, then we will attach the “express.json” middleware and “cors”. The “express.json” middleware will be used for sending and receiving “json”. Also, the Node.js server will be permitted to listen on the “5000” port: const express = require('express'); const cors = require('cors'); require('dotenv').config(); const app = express(); const port = process.env.PORT || 5000; app.use(cors()); app.use(express.json()); app.listen(port, () => { console.log(`Server is running on port: ${port}`); }); After adding the above-given code in the “server.js” file, press “CTRL+S” to save the changes and then run your Node server using “nodemon”: > nodemon server From the output, you can see that our server is successfully running on port “5000”: After successfully running the Node.js server on the specified port, move ahead towards the process of connecting the Node.js server to the MongoDB database. For that, you have to create a MongoDB account first.

 How to create MongoDB database in MERN Stack Development

In MERN stack development, having a MongoDB database account is a must-have. Creating a MongoDB account permits you to build a database according to your requirements. After that, you can add a “Cluster” to the newly created database and generate a connection string, which will assist you in connecting the Node.js server to the MongoDB database. So, let’s start this procedure by moving towards the official website of MongoDB: Now, create an account for hosting the database in the “MongoDB Atlas”: You will see the below-given dashboard after MongoDB account creation. Now, click on the “New Project” button which is located at the right side of the dashboard: In the highlighted input field, enter your MongoDB project name and click on the “Next” button: At this point, your MongoDB project is created and you are all ready to build a new database: In the next step, select the provider and the zone for your database. For instance, we have selected “Google Cloud” as a cloud provider and “lowa” as our region. It is also recommended to choose a free tier which turns out great for a sandbox environment. After selecting the required options, click on the “Create Cluster” button to move ahead: For maintaining the MongoDB security, choose an option between “Username and Password” and “Certificate” for authenticating the connection from or to the Node.js. In our case, we have added the username and password: Now, add your IP addresses to the MongoDB whitelist. This option will permit the configured IP address to access the project’s clusters: After setting up the IP address, click on the “Finish and Close” button: Within a few minutes, the created cluster of your MongoDB project will be provisioned:

 How to generate a MongoDB string to connect Node.js server in MERN Stack Development

After setting up the “Employee-mern-project” database, and the newly created “Cluster0”, go to the “Database Deployments” section and select the cluster. After doing so, click on the “Connect” button which is highlighted in the below-given image: Then, you will be asked to choose the connection method for Cluster0. We want to connect our Node.js server to the MongoDB database in MERN Stack application development, so we will go with the “Connect your application” options: Next, select the “DRIVER” and its “VERSION” and then copy the connection string from the bottom of the window:

 How to connect Node.js server to MongoDB database in MERN Stack Development

In MERN Stack development, to connect the Node.js and the MongoDB database, we will use the connection string, which we have copied in from the “Connect to Cluster0” window. To do so, open up Node.js “server.js” file and make sure your server is running: > nodeman server In the next step, we will add “mongoose” library. The “mongoose” Node.js library helps in establishing a connection between the MongoDB cluster and Node.js server: const mongoose = require('mongoose'); Now, we will create a separate “.env” file for storing the MongoDB Atlas “URI” or the “Connection String”. For this purpose, click on the Node.js server folder which is “backend” in our case, and then creates a “New File”: We have named the new file as “.env”: If you do not have the connection string, then copy it from the highlighted section: Then, add the copied connection string as “ATLAS_URI” in the “.env” file: ATLAS_URI=mongodb+srv://linuxhint:<password>@cluster0.8jdc7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority In the added “ATLAS_URI” specify your MongoDB username and password and press “CTRL+S” to save the added changes: Now, add the following code in your Node.js “server” file: const uri = process.env.ATLAS_URI; mongoose.connect(uri); const connection = mongoose.connection; connection.once('open', () => { console.log("MongoDB database connection established successfully"); }) The added code will try to connect with the “MongoDB Atlas” using “mongoose” library and the ALTAS_URI and if the connection get established, it will print out “MongoDB database connection established successfully” on the terminal window: Press “CTRL+S” to save the added changes and then run your Node.js server: > nodemon server The below-given output declares that we have successfully connected our Node.js server to the MongoDB database in the MERN Stack development: Now, we will check out the method of setting up React.js on Client-Side in MERN Stack development.

 How to setup React.js on Client-Side in MERN Stack development

To set up React.js on the Client-side in MERN stack development, the first thing you need to do is to select a directory for the installation of the React.js based project. You can use the “Command Prompt” for this purpose. However, we will utilize the “Visual Studio Code” terminal which will also make it easy to operate with the React.js application. To do so firstly, we will look for the “Visual Studio Code” application and open it: In the opened application, click on the “File” option of the menu bar and select the “Open Folder” option: Now, browse for the folder where you want to place your React.js application-related file. In our case, we have selected the “Employee-mern-project” folder, present in the “Local Disk (E:)”: Next, press “CTRL+SHIFT+`” to open the Visual Studio Code terminal. You can also perform the specified operation with the help of the “Terminal” menu: At this point, we are all ready to set up the React.js application in MERN Stack Development. The execution of the “npx” command with the “create-react-app” option assists you in creating a React.js application. For instance, the below-given “npx” command will create a “mern-emsystem” React.js application which will have all of the required dependencies in its project folder: > npx create-react-app mern-emsystem Wait for a few minutes, as the installation of the packages will take some time: The below-given error-free output indicates that we have successfully installed the “mern-emsystem” React.js application: The Visual Studio code will automatically load the created the Reactjs-application folder in it. Now, we will make some changes in the “index.html” file of the “mern-emsystem” React.js application: The “index.html” file of your React.js application will somehow look like this: Here, “React App” is representing the “title” of our “mern-emsystem” application: We will utilize the created React.js application for developing a Employee Management System with MERN Stack. So, firstly, we will change the title of our “mern-emsystem” React.js application to “Employee Management System” and save the opened “index.html” file: In the next step, we will change the current working directory to “mern-emsystem” using the terminal: > cd mern-emsystem Now, write-out the below-given “npm” command for starting the development of the web server: > npm start As you can see from the output that our “mern-emsystem” project is compiled successfully and ready to view in the browser: By typing the “localhost:3000” in the address bar of our browser we will see the following interface for the “mern-emsystem” React.js application: You can also add change the content of the “App.js” JavaScript file for handling or viewing the components of your React application: For instance, adding the following code in our “App.js” file will save the “Employee Management System” content inside a container: import './App.css';function App() { return ( <div className="container"> Employee Management System </div> );}export default App; From the below-given image, you can see that the added “Employee Management System” content for our React.js application is successfully displayed: That was all about the procedure of setting up React.js application on Client-Side in MERN Stack Development. You can do further customization according to your requirements.

 Conclusion

MERN Stack is a powerful web application framework used for building modern websites and applications. It comprises React.js for developing the front-end, Express and Node.js to create the backend, and MongoDB database to maintain the database. This write-up demonstrated how to get started with the MERN stack. Each procedure is provided, from setting up the React.js application and Node.js server to connecting the server with the MongoDB database.

How to create routes on server-side in Node.js

Routing is the process used on the server-side to respond to client requests. It defines the endpoint (URIs) at the created application’s back end. We can also define routing as the “express” application objects used to correspond to the HTTP methods. Your application “listens” the requests that match the provided method or routes, and then it calls the specified callback function when it finds one. This write-up will demonstrate how to create the routes on the server-side in Node.js. Moreover, the procedure for creating API endpoints based on the CRUD operations will be also provided. So, let’s start!

 How to create routes on server-side in Node.js

We have already created a simple Employee Management System application with the React.js front end, Node.js server and built a connection between the server and the MongoDB database. After doing so, we added two models: “employee.model” and “designation.model” with their related schema. We will now create some routes for presenting the models’ information from the MongoDB database using the “Mongoose” library. The next step is to add the API routes to utilize them for performing the CRUD operations. We will create a “designation” and an “employee” route for demonstration. To do so, firstly, we will create a new “route” folder on the server-side: We will name the newly created folder as “routes”: Next, click on the “routes” folder and select the “New File” option for creating an “employee.js” route file: By utilizing the same method, we will create another route file, “designation.js” in the routes folder: As you can see, we have created two routes file, “employee.js” and “designation.file” in the “routes” folder: In the terminal, execute the following command for setting up the React router as it is the standard library that can be used for routing: > npm install react-router-dom After doing so, add the following line in your Project’s “App.js” file: import { BrowserRouter as Router, Route } from "react-router-dom"; In the next step, open up the “employee.js” file ad add the below-given code in it: In this code, we have added two endpoints. The first endpoint will handle the incoming HTTP “GET” requests on the “/employees/” URL path. Next, the “Employee.find()” method is called for getting the list of Employees from the MongoDB database. This find() method will return a promise, and the result will be returned in JSON format. The second endpoint which we have added in our “employee” route file, will handle the incoming HTTP “POST” requests on the “/employees/add/ URL path. The new employee name will be considered as part of the request. After receiving the new employee name, a new instance of the Employee will be created, and then the “save()” function will save the new Employee record in the MongoDB database. If the specified operation is completed successfully, then the “Employee added!” string will be returned: const router = require('express').Router(); let Employee = require('../models/employee.model'); router.route('/').get((req, res) => { Employee.find() .then(employees => res.json(employees)) .catch(err => res.status(400).json('Error: ' + err));}); router.route('/add').post((req, res) => { const employeename = req.body.employeename; const newEmployee = new Employee({employeename}); newEmployee.save() .then(() => res.json('Employee added!')) .catch(err => res.status(400).json('Error: ' + err));}); module.exports = router; Next, open up the “designation.js” file for creating the designations routes: Now, firstly, we will add the same endpoints which we have added in the “employees.js” routes file. However, this time we will break all three fields “employeename”, “designation”, and “date” from the submitted data: const router = require('express').Router(); let Designation = require('../models/designation.model'); router.route('/').get((req, res) => { Designation.find() .then(designations => res.json(designations)) .catch(err => res.status(400).json('Error: ' + err));}); router.route('/add').post((req, res) => { const employeename = req.body.employeename const designation = req.body.designation; const date = Date.parse(req.body.date); const newDesignation = new Designation({ employeename, designation, date, }); newDesignation.save() .then(() => res.json('Designation added!')) .catch(err => res.status(400).json('Error: ' + err));}); module.exports = router; The previously added endpoints can be utilized for reading and creating the designation items. Now, we will create two routes for the remaining CRUD operations, which are “update” and “delete”. In the below-given code “/:id” GET endpoint will return a designation item that will have the specified item, and it will be deleted using the “delete()” function. The “/update/:id” POST endpoint will update the existing designation items. For the update endpoint, firstly, we will retrieve the existing designation item from the MongoDB database based on the specified id. After doing so, we will set the designation property values, such as “employeename”, “designation”, and “date” to the values received in the request body. Lastly, we will call the “designation.save()” method for saving the updated designation object in our database: router.route('/:id').get((req, res) => { Designation.findById(req.params.id) .then(designation => res.json(designation)) .catch(err => res.status(400).json('Error: ' + err));}); router.route('/:id').delete((req, res) => { Designation.findByIdAndDelete(req.params.id) .then(() => res.json('Designation deleted.')) .catch(err => res.status(400).json('Error: ' + err));}); router.route('/update/:id').post((req, res) => { Designation.findById(req.params.id) .then(designation => { designation.employeename = req.body.employeename; designation.designation = req.body.designation; designation.date = Date.parse(req.body.date); designation.save() .then(() => res.json('Designation updated!')) .catch(err => res.status(400).json('Error: ' + err)); }) .catch(err => res.status(400).json('Error: ' + err));}); Now, let us tell the Node.js server to use the routes we created in the “routes” folder. To do so, we will open the “server.js” JavaScript file of our server-side: This is how our “server.js” file looks like at this point: The code you are going to add should be placed before the “app.listen(port, function() ” line: Now, add the following code in the highlighted section: const designationsRouter = require('./routes/designations');const employeesRouter = require('./routes/employees'); app.use('/designations', designationsRouter); app.use('/employees', employeesRouter); The first two lines in the above-given code will load the router from the “designations” and “employees” files which we have created in the “routes folder,” and then the routers are defined as middleware: Press “CTRL+S” to save the added changes into your Node.js server-side file: After creating the routes on the server-side in Node.js, you can test them using any API testing application such as Postman and Insomnia.

 Conclusion

The process in which the client requests are processed by the server-side of the Node.js is defined as routing. In routing, a route is a section of “express” code that links the HTTP requests such as POST, GET, DELETE, and PUT to a URL pattern or path and then adds a function for handling the pattern. This write-up demonstrated how to create the routes on the server-side in Node.js. Moreover, the procedure for creating API endpoints based on the CRUD operations is also provided.

How to define models on Node.js Server

Creating an interface for the data a critical in developing an application. Your data use case may differ; however, the process to store and access the data is the same. Models exist between your MongoDB database storage and the logic of the application. A good model defined on the Node.js server is based on “schema,” which describes the properties of the model. This write-up will demonstrate how to define models on the Node.js server. Moreover, the procedure of creating Schemas for defining models will be provided. So, let’s start!

 How to define models on Node.js server

Before jumping into Node.js and starting coding related to models, it is important to take a few minutes to think about the data you want to store and its relationships with the different objects. For instance, we were required to create a simple Employee Management system application. For this purpose, we have already created its React.js front end, Node.js server and built a connection between the server and the MongoDB database. Now, we know that we need to store the information related to the employees such as “employeename”. We also need to store more information about the employees, such as their designation, as there might be multiple employees with the same names. When you start defining your models on the Node.js server, make sure to create separate models for every “object”. In our “Employee-mern-project” application, our candidates for the models are “employee” and “designation”. An Employee Management system can have other models; however, for the demonstration purpose, we will only create the specified models in our Node.js server.

 How to create the Schema to define models on Node.js server

Mongoose” is a Node.js library that permits the users to access the data from the MongoDB database in an object-oriented fashion. In the next step, you have to create a schema for defining a model. Then, you will register the added model with the help of “Mongoose”. After doing so, you can use the defined models throughout the application. Now, we will select the Node.js server folder, which is “backend” in our case, and from the drop-down menu, we will click on the New Folder option: Now, we will name the newly created folder as “models”. This “models” folder is created to store the “employee” and “designation” models in it: In the next step, we will create a new JavaScript file in the “models” folder and will name it “designation.model.js”: Now, add the following code in the “designation.model.js” file: const mongoose = require('mongoose');const Schema = mongoose.Schema;const designationSchema = new Schema({ employeename: { type: String, required: true }, designation: { type: String, required: true }, date: { type: Date, required: true },}, { timestamps: true,});const Designation = mongoose.model('Designation', designationSchema); module.exports = Designation; The added code will create a designation schema having three fields, “employeename”, “designation”, and “date”. Also, the “timestamp: true” option will create “createdAt,” and “updatedAt” fields for the “designations” model and these fields will be automatically updated when the “designation” model changes: To create an “employee” model, we will add another file in the “models” folder: As you can see “employee.model.js” JavaScript file is now created: To create an “employee” model, add the following code in the “employee.model.js” file: const mongoose = require('mongoose');const Schema = mongoose.Schema;const employeeSchema = new Schema({ employeename: { type: String, required: true, unique: true, trim: true, minlength: 5 },}, { timestamps: true,});const Employee = mongoose.model('Employee', employeeSchema); module.exports = Employee; Our “employee” schema only comprises a single field called “employeename”. We also have added some validations such as the employeename is required, it must be unique and at least five characters long. Also, white space at the end of the employeename will be trimmed off: Press “CTRL+S” to save the added code, and the created models are all ready to use!

 Conclusion

The model you define in the Node.js server is an abstraction of the data in your MongoDB database, which is represented as a document. Because of this abstraction, you may use the “Mongoose” schemas to construct a blueprint of how you want the added data to look and behave. This write-up demonstrated how to define models on the Node.js server. Moreover, the procedure of creating Schemas for defining models is also provided.

How to Get and Modify Element’s Attributes, Classes, and Styles through JavaScript

Oftentimes, webpages need to change their elements or how their elements look depending upon the user’s actions or choices. Changing a webpage’s elements, attributes, classes, and styles is all done with the help of the DOM (document object model). The DOM has been set as a standard on how every browser will interpret the HTML webpage and how it will access the different elements on the webpage by W3C (World Wide Web Consortium). JavaScript also interacts with the elements of an HTML page by using the DOM, and in this post, we are going to learn how to access HTML elements with JavaScript and how to change their attributes, classes, and style using JavaScript. So, let’s first create an HTML page with various elements on it by using the following lines of code: <center> <div id="changeStyle"><p>Change My Style</p></div> <div id="changeAttr"><p>Change My Attribute</p></div> <div id="changeClass" class="myClass"><p>Change My Class</p></div></center> These lines of code will give us the following webpage:

 How to get elements

Before we look at how to change elements using JavaScript, we first need to know how to get elements. Well, to get element’s reference, we can use one of the various functions that are provided by JavaScript such as: getElementById() getElementByClassName() getElementByName() getElementByTagName() getElementByTagNameNS() They are all pretty easy to use and understand by their name. Suppose we have an element inside our HTML with an ID of “xyz”, to access the data of this element we would use the following line in the JavaScript file or script tag: var obj = document.getElementById("xyz"); Similarly, if we are trying to access an element by using its className we would use the getElementByClassName() function.

 Changing Style of an Element

Looking at our HTML file, we know that the div that says “Change my style” has the id of “changeStyle”, so we are going to access that with the following line: var cs = document.getElementById("changeStyle"); Now, that we have our element reference in the variable “cs” we can access its style function using the dot-operator and from there we can change its different style values. For example, if we were to change the background color to yellow, we would use the line: cs.style.backgroundColor = "yellow"; After running the HTML file, you will see the following output: You can see in the picture above as well, that we were able to change the style of the element.

 Change the class of an element using JavaScript

We have the element with the id “changeClass” that has a class of “myClass”, to change the class of this element the first thing that we need to do is to refer to this element by using the following line of code: var cc = document.getElementById("changeClass"); Now that we have the element reference in the variable “cc” we can access its classes attribute by using the classList() function. To add a new class “newCLass” in the same variable we can use the following line of code: cc.classList.add("newClass"); If you open up the developer’s console and check the class attribute, you will find the following result: As you can see, you were able to add another class to the class attribute of the element by using JavaScript. If you want to remove an already existing class from the list, you can use the following line of code: cc.classList.remove("myClass"); After executing the above line, you will see the following results in the developer’s console: And there you go; you were able to remove a class from the classes list of an element using JavaScript.

 Changing Element’s Attribute

JavaScript has a function called the “setAttribute” which allows the user to change the value of any attribute of the element whether it may be a “Class” attribute or an “id” attribute. For example, to change the class of an element, let’s first point to the element that says “change my attribute, we use the following line of code: var ca = document.getElementById("changeAttr"); And then we can use the “setAttribute” function like: ca.setAttribute("class", "hello"); Now, we can observe this change in the developer tools like We can even assign our own attributes to the element by using the function, for example, if we want an attribute of “newAttr” to this element with a value of “done”, we can add that by using the following line of code: ca.setAttribute("newAttr", "done"); And if we observe the element in the developer console, we can see the following result: As it is clear in the image above, we were able to add a new attribute named “newAttr” to our element using JavaScript.

 Conclusion

JavaScript provides various features and functions that help us modify various properties and attributes of an HTML element. All of these changes to an HTML element are done with the help of the document object model (DOM) as JavaScript interacts with the DOM to alter the properties of an element. Today, in this post, we learned how we can use JavaScript and get a reference to an element and then with the help of that reference how we can change the styling of that element, the class of the element, and how we can alter the attributes of the element. Along with these alterations, we even learned how can we add a new attribute of our choice to an HTML element.

How to make a calculator program

If you are new to JavaScript or getting started with JavaScript, then it is best to start by implementing a small and easy calculator program. In this post, we are going to learn how to make a very basic yet functional calculator using JavaScript. To take inputs and to display the output to the user, we are going to be using the prompt and the alert functions of the browser respectively. There are two main ways of implementing the functionality of a calculator, first is by using the if-else statements, and the other way is to use the switch statements we are going to cover both of them.

 Step 1: Set up the environment

Create a new HTML file, link a script.js file using the script tag and execute the HTML file so that it runs on the browser, the script tag looks like this: <script type="module" src="script.js"></script> And the HTML file contains these lines: <center> <div><p>A simple calculator</p></div></center>

 Step 2: Writing the JavaScript code

The first thing we need to do in our JavaScript code, is to notify the user to input an operator (* , – , + , /). To do that, we create a new variable and prompt the user for a new input which will be placed in that variable: const operatorVar = prompt("Enter the operator that you want to use (*, -, +, \ )"); Next step is to ask the user for the operands on which this operator will work, we do that using the following lines of code: const operand1 = prompt("Enter the First Value");const operand2 = prompt("Enter the Second Value"); We need to confirm that the user didn’t make any wrong inputs with the following lines of code: function isDigit(input) { var integer = true; for (var char of input) { if (char `9`) { integer = false; } } return integer;}if (isDigit(operand1) == false) { alert("Wrong input at operand 1| Not an integer Value");}if (isDigit(operand2) == false) { alert("Wrong input at operand 2| Not an integer Value");} Next up, we need to check which operator was given by the user by using the if-else statements, perform the required operations and store the result in a new variable: if (operatorVar == "*") { result = operand1 * operand2;} else if (operatorVar == "-") { result = operand1 - operand2;} else if (operatorVar == "/") { result = operand1 / operand2;} else if (operatorVar == "+") { result = parseInt(operand1) + parseInt(operand2);} We need to check for a wrong operator as well, for that we will simply use the else statement and alert the user that a wrong input was made: else { alert("Invalid Operator");} The last step is to display the result variable to the user using the alert dialogue box: alert("The result is : " + result); You are done with coding the calculator on JavaScript.

 Step 3: Testing the calculator

To test the calculator you just coded, simply run the HTML file and type in the prompt boxes as they appear as shown in the gif below: As you can see the test was a success because our calculator works perfectly fine, the complete Code snippet is as: const operatorVar = prompt("Enter the operator that you want to use");const operand1 = prompt("Enter the First Value");if (isDigit(operand1) == false) { alert("Wrong input at operand 1| Not an integer Value");}const operand2 = prompt("Enter the Second Value");if (isDigit(operand2) == false) { alert("Wrong input at operand 2| Not an integer Value");}var result;if (operatorVar == "*") { result = operand1 * operand2;} else if (operatorVar == "-") { result = operand1 - operand2;} else if (operatorVar == "/") { result = operand1 / operand2;} else if (operatorVar == "+") { result = parseInt(operand1) + parseInt(operand2);} else { alert("Invalid Operator");} alert("The result is : " + result);function isDigit(input) { var integer = true; for (var char of input) { if (char `9`) { integer = false; } } return integer;}

 Step 4: Using Switch instead of if-else

To use switch instead of if-else simple replace the if-else statements with the following lines of code: switch (operatorVar) { case "*": result = operand1 * operand2; break; case "/": result = operand1 / operand2; break; case "+": result = parseInt(operand1) + parseInt(operand2); break; case "-": result = operand1 - operand2; break; default: alert("Invalid Operator!"); break;} The complete code snippet is as: const operatorVar = prompt("Enter the operator that you want to use");const operand1 = prompt("Enter the First Value");if (isDigit(operand1) == false) { alert("Wrong input at operand 1| Not an integer Value");}const operand2 = prompt("Enter the Second Value");if (isDigit(operand2) == false) { alert("Wrong input at operand 2| Not an integer Value");}var result;switch (operatorVar) { case "*": result = operand1 * operand2; break; case "/": result = operand1 / operand2; break; case "+": result = parseInt(operand1) + parseInt(operand2); break; case "-": result = operand1 - operand2; break; default: alert("Invalid Operator!"); break;} alert("The result is : " + result);function isDigit(input) { var integer = true; for (var char of input) { if (char `9`) { integer = false; } } return integer;} All that is left now is to test this code, take a look at the gif below: That is it, you have coded a simple calculator using JavaScript.

 Conclusion

Learning a new language requires you to build real-life applications; when you are starting out with learning JavaScript, a calculator program is really useful and an easy way to get the hang of JavaScript. Today, in this post, we learned how to create a very basic calculator program using JavaScript by using both the if-else statements as well as the switch statements.

How to set up and start using jQuery?

jQuery is one of the most widely used JavaScript libraries of the current time, jQuery allows its users to perform functions that normally require a lot of lines of code with only a few short sentences of JavaScript. The developers of jQuery have wrapped important functionalities that a web developer requires quite often in different functions which he can then implement by simply calling the function and following a specific syntax. But, how to set up jQuery in your project? Well, there are 3 main ways of importing jQuery in your project. These 3 methods are: Downloading jQuery and adding it in your HTML file as a script Using a CDN Hosted jQuery in your project If you are working on a Nodejs project then you can install jQuery from the npm Let’s go over all three of these methods

 Method 1: Downloading and Linking jQuery in your project

The first and the most standard way of setting up and using jQuery is by going over to their official website. On jQuery’s website, there are two different versions available for download, one of the versions is known as the “Production version” and the other one is known as the “Development Version”. The main difference between both of these versions is that the production one is compressed and is the most suitable for live websites while the development one is an uncompressed version for testing out newly released features and beta features as well. Once you have downloaded the version you seem adequate, you need to include the jQuery file in the HTML with the script tag because, at the end of the day, jQuery is JavaScript’s library. For this linking you use the following lines of code: <head><script src="jquery-3.5.1.min.js"></script></head> And with these you are now ready to write jQuery code in your website.

 Method 2: Using a CDN Hosted jQuery in your project

CDN stands for content delivery network, and you can use jQuery which is hosted on a CDN, for example, Google’s CDN. Go to google and search for “jQuery CDN Google” and you will get a link to Google CDN’s jQuery like shown below: Copy this link and paste it inside your HTML File under the script tag, it will look like this <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script></head> Using a CDN hosted jQuery has its own benefits, first and the foremost advantage of using this is that your jQuery is always up-to-date. And secondly, most of the browsers have stumbled on a CDN-hosted jQuery while surfing the internet, so when the client comes to your website, their browser doesn’t need to download the jQuery as it is already present in its cache memory.

 Method 3: Using NPM to install jQuery

jQuery is also available on the NPM library and thus can be installed in a Nodejs project by using the following line in the terminal of the code editor: npm install jquery And if you are working on a yarn-based CLI, you can install jQuery using the following line: yarn add jquery And that is about it on how to set up jQuery, now you can write your code with jQuery included inside it.

 Using jQuery

To demonstrate the usage of jQuery, create a new HTML file and add in the following lines in that file: <center> <div id="demo"><p> I am a text field</p></div></center> With these you will get the following output on your browser: Now, create a script tag and write the following jQuery lines inside it to change the background color of the text field: <script> $(document).ready(function () { $("#demo").css("background", "yellow"); });</script> With these lines you will observe the following change in the output: That’s it, you have successfully set-up and used jQuery.

 Conclusion

jQuery is a must-have JavaScript library when it comes to coding websites because of the fact that this saves tons of time for the developer. jQuery contains frequently used operations for web development which require several lines of code wrapped inside a function that can then be utilized by using the bare minimum amount of code. jQuery can be included inside our project in three different ways and we have covered all three of these ways in this post.

How to setup React.js on Client-Side in MERN Stack development

React.js is considered the top tier in the MERN stack development. It is a declarative JavaScript framework used to develop dynamic client-side applications. It also permits you to create complex interfaces by connecting the components of your data from the backend server and then rendering them as HTML. React also excels at handling data-driven and stateful interfaces with minimal code and other functionalities such as error-handling, lists, forms, events, which you expect from a modern web framework. This write-up will demonstrate how to set up the React.js application on client-side in MERN Stack development. So, let’s start! Note: Make sure you have “Node.js” installed on your system. Install it first before jumping into React.js application development if you do not have it already.

 How to setup React.js on Client-Side in MERN Stack development

Node.js also has an “npm” Node Package Manager, which will install all of the required JavaScript packages in your React.js project. It also comprises a Node Package Tool “npx” tool which you can use for running executable packages. To set up React.js on Client-side in MERN stack development, you first need to select a directory to install the React.js based project. You can use the “Command Prompt” for this purpose. However, we will utilize the “Visual Studio Code” terminal, making it easy to operate with the React.js application. To do so, firstly, look for the “Visual Studio Code” application and open it: In the opened application, click on the “File” option of the menu bar and select the “Open Folder” option: Now, browse for the folder where you want to place your React.js application-related file. In our case, we have selected the “Employee-mern-project” folder, present in the “Local Disk (E:)”: Next, press CTRL + SHIFT + ` to open the Visual Studio Code terminal. You can also perform the specified operation with the help of the “Terminal” menu: At this point, we are all ready to set up the React.js application in MERN Stack Development. The execution of the “npx” command with the “create-react-app” option assists you in creating a React.js application. For instance, the below-given “npx” command will create a “mern-emsystem” React.js application which will have all of the required dependencies in its project folder: >npx create-react-app mern-emsystem Wait for a few minutes, as the installation of the packages will take some time: The below-given error-free output indicates that we have successfully installed the “mern-emsystem” React.js application: The Visual Studio Code will automatically load the create React.js application folder. Now, we will make some changes in the “index.html” file of the “mern-emsystem” React.js application: The “index.html” file of your React.js application will somehow look like this: Here, “React App” represents the “title” of our “mern-emsystem” application: We will utilize the created React.js application for developing an Employee Management System with MERN Stack. So, firstly, we will change the title of our “mern-emsystem” React.js application to “Employee Management System” and save the opened “index.html” file: In the next step, we will change the current working directory to “mern-emsystem” using the terminal: >cd mern-emsystem Now, write out the below-given “npm” command for starting the development of the webserver: >npm start As you can see from the output that our “mern-emsystem” project is compiled successfully and ready to view in the browser: By typing the “localhost:3000” in the address bar of our browser, we will see the following interface for the “mern-emsystem” React.js application: You can also change the content of the “App.js” JavaScript file for handling or viewing the components of your React application: For instance, adding the following code in our “App.js” file will save the “Employee Management System” content inside a container: import './App.css';function App() { return ( <div className="container"> Employee Management System </div> );}export default App; From the below-given image, you can see that the added “Employee Management System” content for our React.js application is successfully displayed: That was all about the procedure of setting up React.js application on Client-Side in MERN Stack Development. You can do further customization according to your requirements.

 Conclusion

React.js is a JavaScript library utilized to develop the front-end of the applications based on MERN Stack. It permits the users to create user interface components and code. Because of its ability to handle the rapid change in the data and build a strong connection with the back-end, it is commonly used in the development of MERN stack applications. This write-up demonstrated the procedure of setting up React.js application on client-side in MERN Stack development.

How to set up the Node server in MERN Stack development

In MERN stack development, the tier which is present in between the MongoDB database and the React.js front-end is the “Express.js”. It can be described as a minimalist, unopinionated, and fast Web framework for Node.js. Express.js framework operates the Node.js server inside it. You can connect to the Express.js functions from your application front-end by sending the POSTs, GETs, or HTTP requests. These specified functions are then utilized to change or access the MongoDB data either via Promises or callbacks. Express.js also offers powerful models for handling HTTP responses, requests, and URL routing. This write-up will guide you in creating, setting up, and running the Node server in MERN Stack development. Moreover, the procedure of installing the required dependencies will be also provided. So, let’s start!

 How to set up the Node server in MERN Stack Development

As we have already mentioned, in MERN Stack development, “Node.js” is used to develop the application’s backend. The JavaScript Environment provided by the “Node.js” permits users to execute the code on the server. It also offers enormous useful packages which can be downloaded with the help of “npm” or the node package manager. To set up the Node server in MERN Stack development, the first thing you need to do is to download Node.js on your system through its official website: Next, use the downloaded file to complete the installation of Node.js. After completing the specified operation, execute the below-given in your Command Prompt: >node -v The above-given “node” command with the “-v” option will print out the current version of the “Node.js” which is installed on your system: After installing Node.js, we will move towards the server’s development procedure. For this purpose, firstly, we will create a base folder and then install all of the required packages or dependencies for the Node server development. For the specified operation, you can use also Command Prompt. However, we will utilize the “Visual Studio Code” terminal, making it easy to work in the Node Server files. In the next step, we will open up our base folder by using the “Open Folder” option of the “File” menu: We have selected the “Employee-mern-project” folder for storing the files related to the Node server of the MERN stack: Now, press “CTRL+SHIFT+`” to open a new terminal window in the Visual Studio code. You can also utilize the “Terminal” menu for this purpose: In the next step, we will create a “backend” folder inside our “Employee-mern-project” root or base folder. To do the same, you can execute the below-given “mkdir” command in the opened terminal: >mkdir backend After doing so, we will move into the newly created “backend” folder to add the server related file and packages in it: >cd backend Inside the “backend” folder, we will create a “package.json” file. The package.json file is the core element of a Node server in the MERN stack development. It comprises your MERN stack project’s metadata and defines the functional attributes that the npm can utilize for executing scripts and installing dependencies. To create a new package.json file for your Node server, type out the following command: >npm init -y

 How to install dependencies for Node server in MERN Stack Development

This section will demonstrate the procedure of installing essential dependencies such as “express”, “cors”, “mongoose”, and “dotenv” for your Node server in the MERN Stack Development. The node package manager or “npm” can be used for installing the specified dependencies in the following way: >npm install express cors mongoose dotenv Here: “express” is added to install “Express” which is a lightweight web framework for Node.js. It also supports many middlewares, which assists in making the code easier and shorter to write. “cors” is an acronym for Cross-Origin Resource Sharing. This package permits AJAX requests to access the resources from the remote hosts. “mongoose” is added to install the “mongoose” package. The mongoose package helps the Node server interact with MongoDB in MERN stack development. Lastly, the “dotenv” package will load the environment variables from the “.env” to the “process.env” file. It also manages the database credentials in a collaborative environment. For our Node server, another package that we will install is “nodemon”. It automatically restarts the node application when you make some changes in the file while developing the Node.js based application: >sudo npm install -g nodemon

 How to run the Node server in MERN Stack Development

Till this point, we have installed Node.js, the required packages, and dependencies. Now it’s time to create and run the backend Node.js server. To do so, click on the “backend” folder, and from the drop-down menu, select the “New File” option: Here, you can a new “server.js” JavaScript file is added in the backend folder: Now, in the “server.js” file, we will create an “express” server, then we will attach the “express.json” middleware and “cors”. The “express.json” middleware will send and receive “JSON”. Also, the Node.js server will be permitted to listen on the “5000” port: const express = require('express');const cors = require('cors'); require('dotenv').config();const app = express();const port = process.env.PORT || 5000; app.use(cors()); app.use(express.json()); app.listen(port, () =>{ console.log(`Server is running on port: ${port}`);}); After adding the above-given code in the “server.js” file, press “CTRL+S” to save the changes and then run your Node server using “nodemon”: >nodemon server From the output, you can see that our server is successfully running on port “5000”:

 Conclusion

You will need to set up a Node server to compile your JavaScript code before running it on the backend. Express.js is an HTTP framework that resides in the Node.js server and has a lot of out-of-the-box features. With the help of Express.js, fully functional APIs are developed using minimal code. This write-up guided you in creating, setting up, and running the Node server in MERN Stack development. Moreover, the procedure of installing the required dependencies is also provided.

How to Write and Run Your First Node.js Program in Windows

Node.js is JavaScript in runtime, there is a pretty common misconception of Node.js being a JS framework which is not the case. Node.js is the most widely used runtime JavaScript environment as it allows users to run JavaScript code outside of the browser on the local machine and live servers as well. It utilizes the V8 JavaScript engine and provides a development environment for the user. To work with Node.js on your local machine and start executing JavaScript code snippets you need the following things: You must download and install Node.js on your machine Verify Node.js Path in the environment variables of the machine Code Editor (Optional, Visual Studio Code is preferred) A little knowledge of JavaScript

 Step 1: Downloading and Installing Node.js on your machine

To download Node.js, head on over to the official Node.js website If you are working on a Windows operating system then you can download Node.js from the prominent green button, but if you are working with any other operating system then you need to click on the download tabs like On the “downloads” page, you should be able to see different versions for macOS and Linux-based operating systems as well as shown below: Once, you have downloaded the file corresponding to your operating system, click on the file and follow the instructions to finish the installation process: Select the default and features and click on next: And then simply wait for the installation process to finish: Once the setup is done, you can move on to the next step.

 Step 2: Verifying the path and the NodeJS version

Open up your path environment variable, if you are working on a windows-based operating system then you can open up the path by pressing on the window button and typing in “env” like so: Open up the first option that shows up, and then in the new dialogue box click on the button that says “Environment Variables” like so: Click on the “Path” under the system variables tab and click on “Edit”: And make sure you see an entry like: If you don’t see an entry with Node.js, you need to manually add the path to the installation directory for the Node.js. To check the node and NPM version, open up a command prompt and run the following commands: node --version npm --version You should be able to see the version of the node as well as the NPM on your machine like so:

 Step 3: Writing and Executing JavaScript Code on your machine

Open up the code editor, and create a JavaScript file to demonstrate we are using the Visual Studio Code editor: Type in the following lines of code inside the file: var name = "LinuxHint"; console.log(`Hello World! This is ${name}`); And inside the terminal type in the following command to run our file which is named as “firstCode.js”: node firstCode.js You should be able to see the following output on your terminal or console: That is it, you have successfully run your JavaScript code wit Node.js, now all that there is left to do is to play around with JavaScript and start deploying your code with Node.js.

 Conclusion

Node.js is the most promising and the most widely used JavaScript runtime environment and a must-have if you want to execute JavaScript code outside of the browser’s console, To write your first code in Node.js you first need to download and install Node.js from their official website and then run your JavaScript with Node.js environment with the help of a code editor like Visual Studio Code. Node.js can be further mastered to deploy APIs on live servers.

Selection Sort

The selection sort algorithm sorts the list by finding the smallest number from the unsorted list and moving it in the sorted list. Selection sort divides the actual list into two lists, one for sorted numbers while the second list is for the remaining unsorted numbers, initially we considered the whole list as an unsorted list. Selection sort works on a very basic philosophy that is to find the smallest number in the array and swap it to the initial position (0th index), then again find the second smallest number from the remaining unsorted array and place it to the appropriate position (first index) and so on, in this way finally, we will get a sorted array. In this article, we will discuss how selection sort works, for this purpose we will consider an example to explain each step for sorting an array using selection sort.

 How Selection Sort Works

For instance, consider the following array and sort it using selection sort:

 Step 1

Initially, we have an array of five elements, at index zero we have a value ‘9’, and we will compare it to the next index, if the value of the first index is less than the value of zero-index then next we will compare the value of index 1 to the remaining array elements. We compare ‘1’ with ‘8’, ‘1’ is less than ‘8’ so again we will compare ‘1’ with the value of the next index (3rd index), ‘1’ is less than ‘2’. It means again ‘1’ will be compared with the last index where we found a value ‘4’ which is also greater than ‘1’. So step by step we compare 1 with each element of the array, as a result, we witnessed that ‘1’ is the smallest number among all the array elements. So finally we got a sorted value for the index 0.

 Step 2:

Now after step 1 the value at index zero is sorted, so we have two arrays now, at the left side a sorted array and on the right side an unsorted array: We will sort the unsorted array, so initially we will compare index one with index two, we found ‘9’ is greater than ‘8’ As ‘8’ is less than ‘9’, so from here we will compare the value of index 2 which is ‘8’ with the other array elements. Now ‘8’ is compared with ‘2’ ‘2’ is less than ‘8’ therefore in the next iteration we will compare ‘2’ with the last array elements. Compare ‘2’ with ‘4’: So, ‘2’ is the smallest element among all the unsorted array elements, so, will be swapped at the second index, resultant array after the second step will be:

 Step 3

So far we have 2 elements sorted while still, three elements are unsorted, now we will sort the remaining unsorted elements of the array, for this purpose, compare the value of index 2 with the value of index 3, so there will be no change as ‘8’ is less than ‘9’ and in next iteration, we compare ‘8’ with the value of final index. Compare ‘8’ with ‘4’, here ‘4’ is less than ‘8’ and ‘4’ is the last element of the array, therefore ‘4’ will be swapped with ‘8’: and the updated array will be:

 Step 4:

Now, the first three elements are sorted, compare the value of index 3 with the value of index 4, here ‘9’ is greater than ‘8’ and there is no more element left in the array for the comparison, therefore we swapped the value of forth index with the value of the third index: Finally, we get a sorted array, moreover, if someone is instructed to sort in descending order then it will be done in reverse order by finding the maximum value.

 How to implement Selection Sort

Now, we will conclude the working of selection sort in terms of each step or each pass and then we will implement the same concept. After completing the first step, we get minimum value at 0th index, in the second step second smallest number is shifted at the first index, similarly, we get a proper number at the proper index after completing the third and fourth step, we don’t need to perform sorting for the last index as we have only one element left and if all the prior elements in the array are sorted then the last element will also be sorted. Hence, we concluded that we require a total of “n-1” passes to sort an array. Now we will implement this concept of selection sort: function selection_Sort(input_Array) { let array_length = input_Array.length; for(let i = 0; i < array_length; i++) { let smallest = i; for(let j = i+1; j < array_length; j++){ if(input_Array[j] < input_Array[smallest]) { smallest=j; } } if (smallest != i) { let temp_val = input_Array[i]; input_Array[i] = input_Array[smallest]; input_Array[smallest] = temp_val; } } return input_Array;}const input_Array = [9, 1, 8, 2, 4]; selection_Sort(input_Array); console.log("Final sorted array : ",input_Array); In the initial part of the code, we utilize the “.length” property to check the length of the actual array and store it in a variable “array_length” then we iterate the loop until it reaches the “n-1” index. In the loop initially, we consider that the current index has the smallest value, therefore, we set “smallest=i” and next we use another for-loop to compare the current value to the remaining values of the array, and the loop will start from is “i+1”. Next, we write the code for swapping the element once we found the smallest element in the array. Finally, we utilized the console.log function to print the output on the browser’s console:

 Conclusion

In this article, we have learned how to sort an array using selection sort. In the selection sort algorithm, we pick the first element of the list or array and compare it with the rest of the array elements when we found the smallest element we shift it to the initial index then shift the second least element to the first index, and so on, as a result, we got an array where the sorted elements are present at the left side and the unsorted elements are present at the right side of the array. In this way, a final sorted array is constructed using selection sort. We understand the logic behind the selection sort algorithm by considering an example and explaining its working step-by-step. Once we understand how selection sort works then we implement it.

Conditional Statements

Conditional statements are responsible to execute a piece of code depending upon some conditions. Most frequently the conditional statements are used in decision-making scenarios. In this post, we will address the conditional statements thoroughly. In JavaScript, different conditional statements are available to perform different operations. Various types of conditional statements are listed below: The “if” statement is used to test whether a block of code can run or not depending on the condition. i.e. if the condition for “if-statement” is true then, in this case, the statements within the body of “if-statement” will run else not. Where the “Else” statement will execute only if the same condition is false and a piece of code written inside the body of the “else-statement” will execute in this case. “Else if” can be utilized to define a new condition i.e. if someone wants to check multiple conditions (more than 2 conditions) then the “else if” statement will be used.

 JavaScript if Statement

Syntax of if-statement: if (condition){// body will execute only if the condition is correct.} To understand the working of if statement let’s consider the example that prints “well done” if marks are greater than 85: var marks, output; marks= prompt("Enter you marks");if (marks > 85) { output = "Well done"; console.log(output); }} We take the input from the user using the prompt function and assign the user’s input to the variable “marks”. Next, the value stored in the “marks” is tested using the “if statement”: When you run this code a pop-up window will appear as shown in the below-given screenshot: If the value entered by the user is greater than 85 then it will show an output “Well done”: In this example, we didn’t specify anything for the false condition. So, if the user enters the false condition, let’s say the user enters 55 it wouldn’t show any output instead it will show a blank page because we didn’t specify anything for false conditions. Now we will extend the above-given example with the “else” statement in order to tackle the false statement.

 JavaScript else Statement

Syntax of else statement is mentioned below: if (condition){// body will be executed only if the condition is true.}else{// else part will run in that case when the condition is not true. We will extend our program to print “well done” if marks are greater than 85 and print “better luck next time” if condition is false: var marks, output; marks= prompt("Enter your marks");if (marks > 85) { output = "Well done"; console.log(output); }else{ console.log("better luck next time");} When we run this code a pop-up window will appear asking the user to enter the marks: Now if the entered marks are greater than 85 it will show “well done” else it will show “better luck next time”. Here, we enter 56 so the output will be:

 JavaScript else if Statement

Now we will use else if to specify a new condition for our program if marks are greater than 85, print “well done” else if marks are greater than 50 but less than 85 then print “Good” else print “better luck next time”: var marks, output; marks= prompt("Enter you marks");if (marks > 85) { output = "Well done"; console.log(output); }else if (marks> 50 && marks<= 85){ console.log("Good"); }else{ console.log("better luck next time");} When we run this code a pop-up window will appear, now this program will tackle three conditions first if the user enters greater than 85 marks then it will show a message “Well done”, else if the user enters marks greater than 50 but less than or equal to 85 then it will display a message “Good” else it will show a message “better luck next time”. Here, we entered 67: The output will be:

 Conclusion

Conditional statements are commands or conditions that are used for decision-making purposes. These statements perform various actions based on the conditions. This article presents a detailed overview of conditional statements with examples. Initially, we determine the conditional statements next we consider their types. Thereafter we took some examples and understood the conditional statements along with their types. Finally, we implement these examples and achieve the desired output on a live server.

Mutable and Immutable Data

The term mutability means changeable, the concept of mutability can be applied only to objects and to arrays. Mutability’s concept can’t be applied to primitive data such as string, boolean, number, etc. While immutable data refers to primitive data whose state can’t be changed. In this post, we will understand the difference between mutable data and immutable data with the help of some examples. Before heading towards mutable data or immutable data, initially, we need to clarify the concept of storing data variables. The variables are capable of storing two types of values either primitive type or reference type. Total seven primitive data types are available while there are three reference data types. The main difference between them is, in primitive data type the memory is allocated in the stack while in reference data type the memory is allocated in the heap. So, in short, the primitive data type is the base data type while the reference data type is the object made up of several features and these objects are passed as a reference.

 Mutable data

Mutable objects can be modified or revised after their creation but must remember, an object may have two references, and it’s also possible that there are two objects with the same properties. So, multiple references for one object and two objects with similar characteristics are two different things.

 Implementation of mutable data

Let’s consider an example to understand the mutability. let employee1 = { name: "Joe Clarke", age: 35, id: 123, city: 'London' }; let employee2 = employee1; let employee3 = { name: "Joe Denly", age: 25, id: 121, city: 'Birmingham'}; console.log("check Whether employee1=employee2", employee1===employee2); console.log("check Whether employee1=employee3", employee1===employee3); We created an object named employee and assigned it some properties, in the second line another object was created named employee2 and we assigned it employee which means the employee2 would have the same properties as employee. Then we create another employee and we assign it some different properties. Next, we checked whether “employee2” has the same properties as “employee” or not. Output of above code will be: Now, let’s see what happens if we change the value of “employee1”, will it affect the properties of “employee2”? Let’s modify our code: let employee1 = { name: "Joe Clarke", age: 35, id: 123, city: 'London' }; let employee2 = employee1; employee1.name = "Dean Elgar"; console.log("updated values of employee1 : ", employee1); console.log("updated values of employee2 : ", employee2); Let’s modify the previous example, for instance, change the employee1 name from “Joe Clarke” to “Dean Elgar”, and check whether it affects the name property of employee2 or not. The output for our modified code will be: From the above-given output, we can see that changes that we make in the property of employee1 affect the value of employee2 as well, this happens because employee2 was created with the reference of employee1.

 Immutable data

Immutability refers to the primitive values like string, or number, etc and, we can’t modify them but we can reassign them with some new values.

 Implementation of immutable data

The below-given example will help you to understand the immutable data types. var employee1= 'Daniel';var employee2= employee1; console.log("name of first employee : ", employee1); console.log("name of second employee : ", employee2); We created a variable and assigned a value to it. Then we created another variable and assigned it the first variable as highlighted in the below-given screenshot. Now let’s examine the output, you will see both variable shows same output: Now change the value of “employee2” and observe, will it change the value of “employee1” or the value for the first variable will remain the same: var employee1= 'Daniel';var employee2= employee1; console.log("name of first employee : ", employee1); console.log("name of second employee : ", employee2);var employee2 = 'Bryn'; console.log("updated name of 1st employee : ", employee1); console.log("updated name of 2nd employee : ", employee2); We assign ‘Bryn’ to the second variable: Now, observe the output: The example clarifies that when we changed the value of employee2, we observed that changing the name of the second variable doesn’t affect the value of the first variable which means JavaScript treats both of them as separate variables, and it actually reassigns the value to the second variable. We will consider another example to figure out the immutable data. var str = "hello"; console.log("original string : ", str); str.toUpperCase(); console.log("string after toUpperCase method : ", str); We took a string variable and assigned it a value “hello” then we used a string method “toUpper”. Upon running the program we observed that it didn’t change the string because strings are immutable data types and they can’t be modified after creation. The output of above-given code will be: You can noticed that toUpperCase doesn’t change the lower case letters to the upper case letters because we can’t modify the immutable data after its creation.

 Conclusion

Mutable data can be modified at any point while immutable data contradicts with the mutable data which means the mutable things can’t be changed. In this post, we explained the difference between primitive data types with reference types. Then we understand the idea of mutable and immutable data, for this purpose we took some examples and implemented them. Finally, we can conclude that if we change a value of the reference variable it will mutate the original value as well but the primitive variable doesn’t mutate.

How to Create a Fade-In Animation Effect with JavaScript and CSS

Animations, Transitions, and 3D effects are nothing less than an eye-catcher. Whenever you are building your website or a project, you don’t want it to get lost in the cluster of millions of websites that are available on the internet. You want it to stand out, you want it to amuse its users and get stored in their subconscious minds. To make your web pages more intriguing, you need to utilize various animations and page transition effects. One of the popular and extremely interesting animation effects is the Fade-in and Fade-out animation, which can be implemented using JavaScript and HTML \ CSS.

 Step 1: Set up the basic page

Create a new HTML on your preferred code editor, create a script.js file and a style.css file as well like shown: Inside the HTML file, link the CSS file and the script.js file using the following lines before the body tag: <script type=" module" src="script.js"></script><link rel=" stylesheet" href="style.css" /> Now, we are going to implement a fade-in animation on an image, and for the image, we are going to be using a royalty-free image from Unsplash. You can create an image tag and a button that we will use to fade in and fade out the image with the following lines: <center> <img id="Image" src="https://images.unsplash.com/photo-1640273837947-ea830d50c191?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2072&q=80" /> <br /> <button id="myButton">Fade Effect</button> </center> Notice that we have given the id “Image” to the image and the id of “myButton” to the button that we are creating. Since the image is quite large, we are going to set a particular height and width in the CSS file using the following lines: #image { height: 200px; width: 200px;} Your page should look like this: We have our image in the center of the screen and right beneath the image we have our button.

 Step 2: Modifying the CSS File

There are many ways to implement a particular animation using CSS and JavaScript, but for this particular post we are going to be playing with classes and the opacity attribute of the CSS. Modify your CSS file with the following lines: #image { opacity: 1; transition: opacity 0.3s ease-in-out; height: 200px; width: 200px;} #image.fade { opacity: 0;} To explain what we are doing in the above lines: We are simply putting the opacity of the image to 100% at the start and if the image has an active class “fade” then opacity will change to 0%. But, this opacity change will happen in an instance, to make an animation-like effect we use the transition attribute and set it to 0.3s. Now, all we need to do is write some script that will toggle the class “Fade” from the image

 Step 3: Toggling Class with JavaScript

In the script.js file, we are going to first fetch the image element and store it inside a variable, and then we are going to toggle the class but all of this should be done upon the button press. So, append the following lines in the script file: let image = document.getElementById("Image"); document.getElementById("myButton").onclick = function () { image.classList.toggle("fade");}; So, with this we should be able to implement the fade-in animation and fade-out transition as well.

 Step 4: Testing our animation

The last step is to run the HTML file on our local machine and test out the animation upon button press, you should see the following output: As you can see in the above gif that our animation is working perfectly.

 Conclusion

Animations can easily be implemented with the use of JavaScript along with HTML and CSS to make webpages look much more attractive and eye-catching. In this post, we learned how to make a fade-in and a fade-out animation on an HTML element by assigning different CSS properties on the class of the element and then toggling the classes using JavaScript.

jQuery Events | Explained

jQuery is a JavaScript library that has been designed to wrap the most commonly used JavaScript functionalities into different functions. This allows the user to write concise and time-saving code, this is the main reason for the popularity of jQuery over other available JavaScript libraries. jQuery is designed to deal with events on the web page as well, events (if you are not already familiar) are user actions that cause a web page to react. To better explain events, we can say that any action that a web page can respond to is known as a webpage event for example mouse-over, click, document loading.

 jQuery Events | Syntax and event methods

The syntax of jQuery events is to use a dot-operator after the factory function $() which contains the selectors. $("p").click(); With the above line, an event listener is created, the next step is to define what to do when that specific event executes. To do that, define the function inside the parenthesis of the event such as: $("p").click(function(){// Body of the function});

 jQuery Events | Examples

To demonstrate the working of jQuery events and event handlers we are going to set up an HTML webpage with google CDN hosted jQuery included in its script tag: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> The HTML webpage contains these lines to set-up our testing webpage: <center> <h1>I change color on load</h1> <div><p id="hello">Hello! I am LinuxBot</p></div> <button>Click me!</button> <p id="dblClick">Double Click me!</p> <p id="hide">Click to Hide me!</p></center> If you run the HTML file, you will get the following result on the browser: The first event that we are going to go over is the document-on-ready event. This event is automatically executed when the DOM verifies that the webpage has been completely loaded and is not waiting for any further actions or responses. So, we are going to change the background of the <h1> tag upon document load, with the following lines of code: $(document).ready(function () { $("h1").css("background", "red");}); You will get the following output: As you can see, we were able to change the background color of the h1 with jQuery events. The next event is going to be the button press, we are going to prompt the user for his name upon button press. Use the code: $("button").click(function () { var Xyz = prompt("Enter your full name");}); You get the following output on pressing the button: As you can see, upon clicking the button that says “Click me!”, a prompt dialogue box was shown asking for the user’s full name. Mouse click events are pretty common, but something which is widely used is the double click event. To demonstrate this, we are going to display a message on the screen as an alert when the user double clicks on the paragraph with the id “dblclick” with the following lines of code: $("#dblClick").dblclick(function(){ alert("Have a nice day!");}) With the above lines, the output is as Upon double-clicking on the text, a new alert dialogue box was shown to the user with a greeting. We can even use the “this” reference when working with jQuery events, to demonstrate we are going to hide the text with the id “hide” upon click. We do this by using the following lines of code: $("#hide").click(function () { $(this).hide();}); You get the following output upon clicking the text that says “Click to Hide me!”: The text was hidden upon clicking on it once.

 Conclusion

jQuery library provides the functionality to manage and react to web-page events that is the reason why jQuery is referred to as “Tailored” for event handling. jQuery events are added to the jQuery selector function ( $() ) by using a dot operator, this creates an event listener on that element that listens for a particular event. To perform an action based on this event you need to create a function that tells the web page what to do for that specific event. This function is commonly written within the parenthesis of the event listener.

jQuery Selectors | Explained

JavaScript is most commonly used for manipulating the HTML elements of a webpage by accessing them with the help of the DOM (document object model), it can even be used to display animations and other effects as a result of a certain action done by the user. To do all this, JavaScript first needs a reference to the HTML element that we want to manipulate. Selecting the elements of the HTML webpage can take a few lines of code in the JavaScript but with jQuery, the code becomes concise and looks very readable. jQuery supports the selections of almost all the selectors defined in the CS3, as well as provides some built-in custom selectors as well.

 Adding jQuery to our HTML page

To be able to jQuery in our project, we first need to import jQuery by putting a link to a jQuery file in the script tag. The most effective method of importing jQuery is to use a google CDN hosted jQuery, in the HTML file use the following lines in the script tag: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script>

 The Factory Function

The jQuery selector functions are often referred to as the factory function, it starts with a dollar sign “$” followed by round brackets or parenthesis “()”. This factory function is used to refer to an element of the webpage, and you can add an event by using a dot operator. For example: $(document).ready(function(){ // inside the body of the function });

 jQuery Selectors

jQuery selectors or factory functions work on three major selectors namely: Tag ID, Tag Name, Tag Class. Tag Name: This is used to select the name of the element from the dome, for example, if you want to select all the h1 tags. Tag Class: This is used to choose an element with a certain class; for example, if you want to select an element with the class “myClass” you can use $(‘.myClass’) Tag ID: This is used to select an element with a specific ID; for example, to choose an element with an id of “myID” you can use $(‘#myID’)

 Selecting Elements by Name

To showcase the use of jQuery selectors we are going to first go over the selection of elements using the tag name. Suppose you want to select all the <p> tags on a web page and give them a background color of yellow. Let’s create some P tag in the HTML with the following lines: <center> <div><p>A p tag</p></div> <div><p>Another p tag</p></div> <div><p>Yet another p tag</p></div></center> You should see the following output on the webpage: To manipulate the <p> tags use the following script code: $(document).ready(function () { $("p").css("background", "yellow");}); With the above lines, the output will look like this We even have filter selectors; suppose we only want to select the last <p> tag then we can use the following script code: $(document).ready(function () { $("p:last").css("background", "yellow");}); This will give us the following output: As you can see, we were able to select on a specific <p> tag using the filtered name selector.

 Selecting Elements by ID

To demonstrate the ID selectors, we have the following lines in the HTML file: <center> <div><p id="hello">A p tag with the ID hello</p></div> <div><p id>Another p tag</p></div> <div><p id>Yet another p tag</p></div></center> As you can see, the first <p> tag has the ID “hello”, to manipulate this element using its ID, we can use the following script code: As you can see in the image above, we were able to select an element using its id and manipulate its styling property using jQuery id selector.

 Selecting an Element by Class

To select an element using the class, we use the dot before the name of the class in the factory function, to be able to demonstrate the use the jQuery class selector, let’s give one of the p tags some class. Our HTML code will look like this: <center> <div><p id="hello">A p tag with the ID hello</p></div> <div><p >Another p tag</p></div> <div><p class="myClass">Yet another p tag but with some class</p></div></center> To select the class “myClass” and give it a background of red, we use the following script code: $(document).ready(function () { $(".myClass").css("background", "red");}); With the above code, you will see the following output: As you can see, we were able to manipulate the element with the class “myClass” by using jQuery class selectors.

 Conclusion

JavaScript’s most famous library jQuery is highly useful and time saving when it comes to manipulating elements on a webpage, the only pre-req of using jQuery in a project is to add a link to the jQuery library by using a google CDN hosted jQuery. The jQuery consists of a function which is called the factory function which allows users to select elements of the webpage and manipulate their properties. The factory function ‘$(‘ ’)’ works on 3 basic selectors which are namely, ID selector, Name Selector and Class Selector.

How to create a component in React.js

Components are the building blocks of the React application and have an independent piece of some functionality that you can reuse in your project front-end. The component file can comprise the simple JavaScript functions and classes; however, you can utilize them as customized HTML elements. Components are utilized for adding menus, buttons, or any other page content to your React.js front-end, and it is also used for including the markdown and state information. This write-up will demonstrate how to create a component in React.js. So, let’s start!

 How to create a component in React.js

In React.js, components display what we want to see on our React application. A react component can take the “props” or properties as parameters and return a view hierarchy for displaying using the render method. The added code in the render method will define what you want to show on the screen. React.js takes the body of the render method and then displays the results according to it. React applications can efficiently update and then re-render the added components when the data changes. Before creating a component in our React.js application, firstly, we will show you how the interface of our React.js application looks like: For this purpose, we will move into our React.js application folder by executing the following command in the terminal: > cd mern-emsystem At this point, you have to make sure that your React.js application is running on the specified port. If it is not, then write out the below-given command for starting your front-end web server: > npm start Here is the basic interface of our Employee Management System application: Now, open up a new terminal window by clicking the “+” button, which is highlighted in the below-given image: We will utilize the new terminal window for installing the Bootstrap CSS framework for making the styling easier: > npm install bootstrap In the next step, open up the “App.js” JavaScript file, located in the “src” directory: Now, import the “bootstrap” CSS file by adding the following lines: import "bootstrap/dist/css/bootstrap.min.css"; Press “Ctrl+S” to save the added changes and then create a new “Components” folder in the “src” folder: After doing so, we will create a new “Instructions.js” component file: Then, open up the created “Instructions.js” file and add the below-given code in it: Our idea is to create a custom component that will display a heading, some description, and an image related to our Employee Management System React.js application. For this purpose, firstly, we will import the “React” and its “Component” class and the “ems.png” image, which we want to add to this Instructions component. The “Component” base class can be then extended for creating the required components. The “Component” class has various functions that can be utilized to enhance the functionality of the created method and “render()” is one such method. “render()” is used for returning the JSX code which you want to view in the browser: import React, { Component } from 'react';import ems from './ems.png';export class Instructions extends Component { render() { return( <div> <h1>Employee Mern Project</h1> <p>This is an Employee Management System</p> <img src="{ems}" />; </div> ) }}export default Instructions; After adding the code in the “Instruction.js”, press “CTRL+S” to save it and then open up your “App.js” file: Your created React.js component will be of no use until you import it into your “App.js” file and wrap the created components with the angle brackets. Here we have imported the “Instructions” component and added the specified component as “” in the “return()” function of the App(): import React from 'react';import "bootstrap/dist/css/bootstrap.min.css";import Instructions from './components/Instructions';function App() { return ( <div> </div> );}export default App; After importing the “Instructions” component, we will run our React.js application: > npm start From the output, you can see that our “Instructions” component is successfully displaying the added content:

 Conclusion

In React.js, components are the self-contained elements that can be reused across a page. They display what we want to see on our React application. You can also break down complex applications into smaller sections that can be easier to design and manage with the help of components. This article demonstrated how to create a component in the React.js application. Moreover, the procedure of creating and using a custom component is also provided to you.

JSON.parse() and JSON.stringify() | Explained with examples

One of the biggest features of JavaScript is its JSON notation for transferring data, JSON object is perceived by all updated browsers and is used in almost every programming language that is available in the current market. JSON is a very light-weighted and human-friendly data notation that is also readable by programming languages. JSON objects are transferred or read by the program in the form of strings which are called JSON strings. To identify JSON string, simply look for quotation marks on either end of the trivial JSON notation. However, JSON strings need to be converted into JSON objects so that we don’t have to use string operations in our program. Similarly, to transfer data from one program to another – or let’s just say from the server to the client-side – it is best to convert the JSON object back to a JSON string. For these conversions, ES6 JavaScript provided two functions “JSON.parse() & JSON.stringify()”.

 JSON.stringify() and its usage

JavaScript Objects are converted into strings with the “JSON.stringify()”. To demonstrate this function, we are going to need an object which can be created with the following lines of code: var myObject = { name: "John Doe", age: 15, email: "test@test.com", job: "Auditor",}; You can print out this object on the console by using the following line: console.log(myObject); You will get the following output on your console. Now, we can pass this object in the JSON.stringify() function and store it inside another variable using the following line: var converted = JSON.stringify(myObject); This variable can be printed by using the console.log() function: console.log(converted); After executing the following program, you should see the following output on your console: As you can see, we were able to convert the JSON object into a string that can be transferred over a network or stored in some file for later use. The Stringify() function takes 2 additional arguments which are optional but still very useful: one is the function known as the replacer argument second one is called the space argument

 The replacer parameter

The replacer is a function that you create with two parameters: key value, corresponding to the key-value pair of the object. The replacer method is used to either check for a specific value or return another string instead of the original value. The replacer method can also be used to skip a key-value pair from the converted string by returning an undefined value. To create a simple replacer method that will skip the key-value pair from the resulting string if the value of is “Auditor”, for that use the following lines of code: function replacer(key, value) { if (value === "Auditor") { return undefined; } return value;} To create a new resulting string with from our JavaScript object and print it use the following line: console.log(JSON.stringify(myObject, replacer)); You get the following result on the console: As you can see, since the “job” key had the value of “Auditor” therefor it was skipped from the resulting string

 The space parameter

The third argument of the JSON.stringify() function is the space parameter, this parameter takes either a string or a number for the following actions: If a string is passed, then that string gets appended before the key-value pairs If a number is passed, then that number of spaces are added between the key value pairs To demonstrate the spacer argument, we use the following line of code: console.log(JSON.stringify(myObject, null, 10)); You will observe the following result on the console: You can observe the space between each key-value pair (space is marked by the yellow line to make it more prominent) To demonstrate the appending of a string before each key-value pair in the resulting string, use the following lines of code: console.log(JSON.stringify(myObject, null, " A ")); You will observe the following result on the console: The prefixed substring is easily noticeable

 JSON.parse() and its usage

The JSON.parse() function is used to convert a string or more precisely JSON string into a JSON object. To demonstrate this, create a new json string with the following line of code: const string = '{"name":"John Doe", "Age":15, "email":"test@test.com", "job": "Auditor"}'; To create a json object, pass this string in the parse() function and store the resultant object in a new variable using the following line of code: const myObject = JSON.parse(string); To observe this resulting object, use the console log function like so: console.log(myObject); Upon execution, you should observe the following output on your console: You can access the values from this resulting object like any other normal object, try the following line of code to verify this: console.log(myObject.job + " " + myObject.name); You will get the following output on your console: That is it for JSON.parse() function and JSON.stringify() function

 Conclusion

The JSON.parse() function is used to convert a string into a JavaScript object while the JSON.stringify() function is used to convert a JavaScript object into a string. The JSON string is used whenever we want to transfer data from one program to another, within the program, it is better to use the JavaScript object rather than using the string operations. JavaScript provides these two functions as built-in functions, and these functions are supported by all modern-day browsers.

How to Perform Mathematics Using Arithmetic Operators

Mathematical Operators play a very crucial role and also in other well-known programming languages. Numerous mathematical operations are available. Mathematical operators are frequently used to calculate and process numerical data. In this post, we learn about the different arithmetic operators that are available to perform different mathematical operations. Such as addition, multiplication, division, modulus, etc. Arithmetic operators perform an operation and return a value. First, we will understand the concept of operators and operands. The operators are special symbols that symbolize the computations such as addition, subtraction, etc. while the operands are the values upon which operators perform some actions. Consider a very basic example where we want to add two values:

 Implementation of Addition “+” operator

var a=12 + 14; console.log("The sum of two numbers : ", a); In the above example, “+” is a mathematical operator while the numbers (“12” and “14”) are its operands. In this example, we added two values and assign their result to a variable a. “console.log” is a method, that will print the output on the browser’s console. The output of the above example will be: In JavaScript, the values can be literals or variables, or expressions. In the above example, we have literals (12+ 14) while in the next example we will add the two numbers and assign the result to the third variable (a+ b): let a= 12; let b=14; let c=a+ b; console.log("The sum of a and b :" , c); Implement the above code. This example and the previous example will produce the same result: Must remember that “+” will act as a concatenation operator when we add two strings. So, pay attention and use the “+” operator carefully.

 Subtract “-” operator

The “-” operator is utilized to determine the difference of different numeric values. For instance, we consider an example to understand how the “-” operator works.

 Implementation of Subtract “-” operator

var a= 12;var b=14;var c= a - b; console.log(“the value of c : ” , c); Assign a value 12 to variable a, assign 14 to var b, subtract the value of b from the value of a, and assign the result to c. Here we use the console.log function to print the output on the console you can also use the console.log to display the output on the document:

 Multiplication “*” operator

In JavaScript “*” is used to multiply the numerical values.

 Implementation of Multiplication “*” operator

var a= 12;var b=14;var c= a * b; console.log ("the product of a and b is : ", c); c stores the result of a*b and “console.log” will display the value stored in c: The output of the above-given program will be:

 Division “/” operator

In JavaScript “/” is used for the division purpose. It is used to determine the quotient of the numeric values:

 Implementation of Division “/” operator

var a= 12;var b=14;var c= a / b; console.log("The result of a/b is : ", c); Now implement it in the Visual Studio Code: The output for the above-given code will be:

 Modulus “%” operator

The modulus operator is accessible, it is depicted by the percentage sign (%) and it’s also known as the modulo operator, it is responsible to return the remainder value. In programming languages, the modulus operator is used to check wheatear the number is even or odd.

 Implementation of Modulus “%” operator

var a= prompt("Enter a number");if (a%2==0){ console.log("you enter an even number");}else{ console.log("you enter an odd number");} In this example, a variable “a” will take a value from the user. If a user enters an odd value it will print a message “you enter an odd value”. The modulus operator divides the given value with 2, if the remainder is 1 it will show an odd value: If the user enters an even number; Then it will print a message “you enter an even value”:

 Exponentiation Operator

The exponentiation operator is one of the latest operators which is represented with a double asterisk (**). It is utilized to compute the power of a .

 Implementation of Exponentiation “**” operator

var a= 3 ** 4; console.log("3 power 4 is equal to : ", a);

 Implement the above piece of code

The output of the above-given code will be: In JavaScript, an alternate method is also available to find the power of a number.

 Implementation of Math.pow Method

var a= Math.pow(3, 4); console.log("calculate the power using pow function : ", a); math.pow function is utilized in this example to calculate the power of a number. The output of the math.pow method will be the same as the output of the exponentiation operator:

 Increment operator (++)

The “++” operator increments the value of a variable one time. For instance, consider we have a variable whose value is 5, if we apply increment operator on it, then the increment operator will increment its value to 6. The increment operator can be applied only to the variable. We can’t apply the increment operator on numeric values it will result in an error. For example: var a=5; a++; //correct, increments the value one time.5++; //false, it will cause an error.

 Implementation of Increment operator

var a=5; a++; console.log("The incremented value is : ", a); Implement the above code. The output will be:

 Decrement operator (–)

The “-” operator decrements the value of a variable one time. Let’s suppose we have a variable whose value is 5 the decrement operator will decrease it to 4. The decrement operator can be applied only to the variable. We can’t apply the decrement operator on numeric values it will result in an error. For example: var a=5; a--; //correct, value will be decremented to 4.5--; //false, it will cause an error.

 Implementation of decrement operator

var a=5; a--; //correct, value will be decremented to 4. console.log ("The decremented value is : ", a); The above-given code will be implemented as; The output of the above-given code will be:

 Operator Precedence

In JavaScript, the expression is evaluated on the basis of precedence (priority base). The programming languages follow the same precedence as we follow in mathematics. Parenthesis has the highest precedence, then exponents, then multiplication and division have the same precedence, addition and subtraction have the lowest precedence as compared to the other operators.

 Implementation of Operator Precedence

Let’s consider an example to understand the precedence: var a= 2 + 3 * 4 **2; console.log("The result is : ", a); Now we will implement the above code in visual studio code: The output will verify that the above code follows the precedence order. According to this, it will first solve “4 **2” because exponents have higher precedence then it will multiply the result of exponents with the 3 and at the end, it will perform addition. So, the output is:

 Conclusion:

Mathematical operators are very important to perform operations like addition, subtraction, and multiplication, etc., while solving complex expressions, these arithmetic operations follow the same precedence as in regular mathematics. In this article, initially, we determined what arithmetic operations are, their use, then we addressed various mathematical operators, their syntax and implemented them in visual studio code. Furthermore, we have learned about the operator precedence, and finally, we discussed a couple of arithmetic operators particularly for the programming languages such as increment and decrement operators.

How to connect Node.js server to MongoDB database in MERN Stack Development

If you want to develop an application based on MERN Stack that saves any form of the data such as events, comments, user profiles, content, and uploads, you will need a simple database to use with the front-end and back-end. This is the situation where MongoDB comes into play. In the React.js front end, the created JSON documents are sent to the Express.js and the Node.js server, processing them and storing them in the MongoDB database. This write-up will demonstrate how to create a MongoDB account and generate the connection string for your Project cluster. Moreover, the procedure of connecting the Node.js server to the MongoDB database in MERN Stack development will be also provided. So, let’s start! Note: Before connecting the Node.js server to the MongoDB database, ensure that you have set up the Node server and it is running on the specified port.

 How to create MongoDB database in MERN Stack Development

When we think about databases, rows, tables, and other relational concepts come to our minds. MongoDB offers similar principles, although they are referred to differently. For instance, in MongoDB, we have “Collections” instead of tables, “Documents” instead of rows. For storage purposes, MongoDB uses the Binary JSON (BSON) format, and it also offers a wide range of data types supported by the JSON, such as ISODates, Decimal128. In MERN stack development, having a MongoDB database account is necessary. Creating a MongoDB account permits you to build a database according to your requirements. After that, you can add a “Cluster” to the newly created database and generate a connection string, which will assist you in connecting the Node.js server to the MongoDB database. So, let’s start this procedure by moving towards the official website of MongoDB: Now, create an account for hosting the database in the “MongoDB Atlas”: You will see the below-given dashboard after MongoDB account creation. Now, click on the “New Project” button, which is located at the right side of the dashboard: In the highlighted input field, enter your MongoDB project name and click on the “Next” button: At this point, your MongoDB project is created, and you are all ready to build a new database: Next, select the provider and the zone for your database. For instance, we have selected “Google Cloud” as a cloud provider and “lowa” as our region. It is also recommended to choose a free tier that is great for a sandbox environment. After selecting the required options, click on the “Create Cluster” button to move ahead: To maintain the MongoDB security, choose an option between “Username and Password” and “Certificate” for authenticating the connection from or to the Node.js. In our case, we have added the username and password: Now, add your IP addresses to the MongoDB safelist. This option will permit the configured IP address to access the project’s clusters: After setting up the IP address, click on the “Finish and Close” button: Within a few minutes, the created cluster of your MongoDB project will be provisioned:

 How to generate a MongoDB string to connect Node.js server in MERN Stack Development

After setting up “Employee-mern-project” database and the newly created “Cluster0”, go to the “Database Deployments” section and select the cluster. After doing so, click on the “Connect” button, which is highlighted in the below-given image: Then, you will be asked to choose the connection method for Cluster0. We want to connect our Node.js server to the MongoDB database in MERN Stack application development, so we will go with the “Connect your application” options: Next, select the “DRIVER” and its “VERSION” and then copy the connection string from the bottom of the window:

 How to connect Node.js server to MongoDB database in MERN Stack Development

In MERN Stack development, to connect the Node.js and the MongoDB database, we will use the connection string, which we have copied in from the “Connect to Cluster0” window. To do so, open up Node.js “server.js” file and make sure your server is running: > nodeman server In the next step, we will add the “mongoose” library. The “mongoose” Node.js library helps in establishing a connection between the MongoDB cluster and Node.js server: const mongoose = require('mongoose'); Now, we will create a separate “.env” file for storing the MongoDB Atlas “URI” or the “Connection String”. For this purpose, click on the Node.js server folder, which is “backend” in our case, and then create a “New File”: We have named the newly created file as “.env”: If you do not have the connection string, then copy it from the highlighted section: Then, add the copied connection string as “ATLAS_URI” in the “.env” file: ATLAS_URI=mongodb+srv://linuxhint:@cluster0.8jdc7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority In the added “ATLAS_URI,” specify your MongoDB username and password and press “CTRL+S” to save the added changes: Now, add the following code in your Node.js “server” file: const uri = process.env.ATLAS_URI; mongoose.connect(uri);const connection = mongoose.connection; connection.once('open', () => { console.log("MongoDB database connection established successfully");}) The added code will connect with the “MongoDB Atlas” using the “mongoose” library and the ALTAS_URI. If the connection gets established, it will print out “MongoDB database connection established successfully” on the terminal window: Press “CTRL+S” to save the added changes and then run your Node.js server: > nodemon server The below-given output declares that we have successfully connected our Node.js server to the MongoDB database in the MERN Stack development:

 Conclusion

In MERN Stack development, “MongoDB” is used to store the data received from the application front end and then processed by the Node.js server. For creating a connection between your Node.js server and the MongoDB database, you will need a connection string generated by the created project cluster. This write-up showed you how to create a MongoDB account and generate the connection string for your Project cluster. Moreover, the procedure of connecting the Node.js server to the MongoDB database in MERN Stack development is also provided.

localStorage and sessionStorage | Explained

The Web API and the Web Storage API are two of the most useful APIs that are supported by most browsers, The Web Storage API proves two objects the localStorage storage and the sessionStorage which help us store our data into the browser’s memory. Both of these objects allow us to store data locally, with the only difference being that with the sessionStorage object, the data is automatically deleted when the sessional expires, whereas with the localStorage object the data is permanently saved. These objects can be considered as alternatives for cookies and have their advantages over cookies as well, saying that these objects can overtake cookies completely is not true. Cookies can be read by servers and other web applications whereas the data stored locally on your browser can not be read by any server this provides security benefits.

 localStorage and sessionStorage | Syntax

Both of these objects have identical functions with identical syntaxes. The syntax for the localStorage object is defined as localStorage.function(key, value); Similarly, for sessionStorage object, the syntax is defined as sessionStorage.function(key, value);

 Functions provided by localStorage & sessionStorage

Both of these objects from the Web Storage API provide 5 functions and a const variable as: setItem(): To store a new entry in the local storage in the form of key-value pairs getItem(): To fetch an entry from the local storage by using its key clear():To clear the local storage of the browser remove(): To remove a value from the local storage using a key key(): To return the name of the key using its index value length(): A variable that stores the number of entries in the local storage

 localStorage and sessionStorage | Usage

To demonstrate the use of Web Storage API, open the browser of your choice (chrome in our case) and visit a site like www.google.com.

 How to Create/Add data in localStorage using setItem() method

Create a new data entry in the local storage by typing in the following line of code in the console of the browser: localStorage.setItem("Name", "John Doe"); If the command executes without any error, this means that a new entry was successfully made in the browser’s storage. To verify this, go to the “applications” tab in the developer’s tools and expand local storage. You should be able to see the value in the explorer:

 How to Access/Get data from localStorage using getItem() method

To access any entry from the local storage, you can either use a dot-operator with the localStorage object and then enter the key or use the getItem() function. To access the “Name” we just stored, we can either use: var name = localStorage.Name; console.log(name) The output is as: Or we can use the command as shown: console.log(localStorage.getItem("Name")); The output is as

 Permanent storage of the localStorage object | Verification

To verify that the localStorage object stores data permanently (until removed manually), close the browsers that had previously opened up the link where you stored some data (in our case it was google.com) You have ended the golden handshake and terminated the current sessions with the website by closing the browsers, reopen the browser and head over to the same website and then go into developer tools > Applications > Local storage to verify if the data is still there or not: All of the above steps can be done with the sessionStorage Object but remember it will delete all the data when the session expires. Let’s see the demonstration.

 How to create/add data in sessionStorage using setItem() method

We are going to first create a new entry in the sessionStorage with the following line of code: sessionStorage.setItem("Job","Auditor"); The console displays “undefined” meaning the command was successfully executed without any error: We can verify the storage under the session storage tab: Close the browsers, and reopen the same link and then go to developer’s tools > Applications > sessions storage, you will see the following results: You can see that the entry was deleted, this proves that the sessionStorage object only stores data for in the local storage of the browser for only one session.

 Conclusion

The localStorage and sessionStorage objects are used to store data in the browser’s local storage and they are part of the Web Storage API; Both of these objects provide 5 functions to the user that allows the users to create, update, get and delete an entry from the local storage. The difference between the localStorage and sessionStorage object is that the localStorage object permanently stores the data against a website while the sessionStroage object only stores the data for one session.

Object Destructuring, Rest Parameters, and Spread Syntax | Explained

Object destructuring, rest parameters, and spread syntax are all considered to be advanced JavaScript topics. We are going to break them down into simple understandable steps and explain them with examples. All three of these features were introduced with the release of ECMAv6 JavaScript (ES6 JS)

 Object Destructuring

It is the process of taking the “values” from the key-value pairs from an object and placing them into individual variables with a single line of code. This single line of code not only assigns values to the variables but even creates those variables as well. We can say that we are declaring and initializing multiple variables in a single line of code with object destructuring. Syntax of object destructuring: After the variable declaration (const, let, var) place the identifiers of the variables inside the curly brackets and put this whole equation equal to the object that we want to destructure. Remember, the name of the variables should be the same as the “key” of the key-value pairs of the object. const {identifier1, identifier2, identifier3 } = objectName; Note: There is no destructuring “operator”, however, the above statement is referred to as the “destructuring assignment operator” Example: To demonstrate the object destructuring we are going to first create an object by using the following lines of code: phone = { name: 'iPhone', model: '13 Pro', company: 'Apple', popularity: 10} Now that we have our object, we can destructure it into various variables, with the following line of code: const { name, model } = phone; Note: we are only destructuring the object and storing two values with the key “name” and “model”, that is why we need to give the name of the identifier the same as the keys of the key-value pairs. You can even access the values using variables like: console.log("The name of the mobile is: " + name); console.log("The Model of the mobile is: "+ model); The complete code snippet of this example is as phone = { name: "iPhone", model: "13 Pro", company: "Apple", popularity: 10,};const { name, model } = phone; console.log("The name of the mobile is: "+name); console.log("The Model of the mobile is: "+ model); You will get the following output when you run this code: That is it for object destructuring ES6

 Rest Parameters

The rest parameters are used when we are not certain of how many parameters a function should take. We prompt the compiler by using the triple-dot operator before the name of the parameter to make it clear that this is a rest parameter and not a normal parameter. The values inside the rest parameter are stored as an array under the same identifier as the parameter itself. Syntax As mentioned above, we use a triple-dot operator before the identifier in the parameters of a function to make it into a rest parameter function xyz (...paramIdentifier) {// Body of the function}

 Restriction for defining Rest Parameters:

Only one rest param in a function. Must be the last parameter of the function

 Example of Rest Parameters

To demonstrate the use of Rest Parameters with JavaScript we are going to create a simple function that sums up the numbers given to it as arguments with the following lines of code: function sum(a, b){return a+b;} As you can see, this function can only sum 2 numbers, but we want a function that can take an indefinite amount of numbers and sum them up for us, so we change the function to make it look like this: function sum(...numbers) { result = 0; for (value of numbers) { result = result + value; } return result;} As you can see, we are only taking 1 parameter which is the rest parameter that will allow this function to take an indefinite amount of numbers and then we are using the for-of loop to traverse through the values placed inside the array and adding them into each others. All that is left to do is to call this function and print out the return value with the following lines of code: console.log(sum(6, 3, 83, 55, 13, 45)); console.log(sum(1, 2, 3)); You will see the following output on the screen when you execute this code: That is it for using Rest Parameters, we can now move on to our next topic.

 Spread Syntax

It is used to pass on the elements of an iterable object (either an array or a string) to the arguments or the list of arguments as with a single line of code without having the need of manually iterating through that iterable object. Syntax The syntax of the spread syntax is pretty basic, we simply use the triple-dot operator before the variable name while passing it as an argument. (...argumentVariable); Example To demonstrate the use of spread syntax we are going to need a function that we can create with the following lines of code: function addNumbers (a,b,c,d,e){ return a+b+c+d+e;} Now that we have our function, we need an array that will contain our numbers to be added, numbers = [5, 3, 1, 6, 2]; The last thing that is left to do is to pass on this array using the spread syntax into the function with the following line of code: console.log(addNumbers(...numbers)); You should see the following result on your console: As you can see, the elements of the array were successfully passed to the function as arguments with the use of spread syntax.

 Rest parameter vs Spread Syntax

Oftentimes, users get confused between the rest parameters and the spread syntax for passing arguments. This confusion is created due to the fact that the operator for both of these features is the same (dot-operator). To address this confusion, we can say that: If the dot-operator is used in the function definition to define a parameter then it will be called the rest parameter operator. On the other hand, if this operator is used while passing arguments to a function then it will be called the spread operator.

 Conclusion

JavaScript has various features, especially the ECMA v6 release of JavaScript bombarded the programming community with a lot of useful features. Some of these features are: object destructuring, the rest parameters, and the spread syntax. In this post, we have gone through the explanation and usage of these three features along with their examples.

Bubble Sort

Bubble sort is one of the simplest sorting algorithms that compares two side-by-side items and sorts the array in either ascending order or in descending order. Numerous algorithms are available to sort the arrays, such as selection sort, and merge sort, etc. In this article, we will learn how to use bubble sort in order to sort the array elements. Let suppose we have an unsorted array and we are asked to sort the array in any intended order (i.e. ascending, or descending). Then we have multiple sorting algorithms, to sort that array such as bubble sort, insertion sort, etc. For this purpose, we can use any of these algorithms since all the algorithms will produce the same result. This article will address the bubble sort with examples.

 Working of Bubble Sort

It starts working by comparing the left index to the right index. Initially, it will compare the first two indexes of the array (the value placed at index 0 will be compared with the value placed at index 1). The value of the 0th index will be replaced only when the 1st index carries a smaller value than the 0th index’s value. Next, it will compare the value of index 1 with the value of index 2, and so on. Suppose we have the following unsorted array: We know that in arrays indexing starts from 0. So initially, at index 0 the value is 8. The value of index 1 is 3, and 1 is placed at index 3, and so on. Now, we have to sort this array in ascending order as shown in the below-given array: Now, we will explain the working of bubble sort step by step.

 Step 1:

In the beginning, index 0 carries 8 while index 1 carries 3. Since we have to sort the array in ascending order, therefore, the value of index 0 will be replaced with the value of index 1. Now, the updated array will be: Now the value of index 1 will be compared with the value of index 2. The value of index 1 is 8 while the value of index 2 is 1 which is less than 8, so it will be swapped and the array will be modified as: Now, we will make a comparison between index 2 and index 3. The value of index 2 is 8 which is greater than the value of index 3 which is 2 so the values will be swapped: Now compare the value of index 3 with the value of index 4. At index 3 value is 8 while at index 4 value is -1 which means both these values will be swapped: Finally, the value of index 4 will be compared with the value of index 5. Again 8 is greater than 7 so, it will be replaced with 7: Now, the first iteration is complete, and “8” reaches its appropriate position. So, in the next step, the comparisons will be made till the 4th index since the value of the last index is sorted.

 Step 2:

Now, the first two indexes will be compared. The value of the 1st index is less than the value of the 0th index therefore there values will be swapped: Next, we will compare the value of the 1st index with the value of the 2nd index. Here, 3 is greater than 2 so, it will be replaced with 2: Now we will compare the value of the 2nd index i.e. 3 with the value of the 3rd index which is -1. Values will be swapped again since 3 is greater than -1: The value of the 3rd index is less than the value of the 4th index so, it will remain the same: Now the last two indexes are sorted and the values are placed properly on the 4th and 5th indexes.

 Step 3:

Now in this iteration, initially the value of the 0th index will be compared with the value of the 1st index. Here, the value of the 0th index is 1 which is less than the value of the 1st index which is 2. So, these values will remain the same. Next, compare the next two indexes, here the value of the 1st index is greater than the value of the 2nd index therefore, their values will be swapped: The value of the 2nd index is less than the value of the 3rd index therefore, their values will not be swapped:

 Step 4:

Compare the first two indexes. The value of the 0th index is -1, less than the value of the 1st index which is 1 so it will be swapped: Next, we will compare the value of the 1st index with the value of the 2nd index. They are already sorted, so they will remain the same: Finally, our array is sorted in ascending order.

 Implementation of Bubble Sort

Since we understood how bubble sort works, now we will implement this logic using nested loops: function bubbleSort(ary){ let i, j; var flag = false; for(i =0; i < ary.length; i++) { flag = false; for(j = 0; j ary[j + 1]) { var temp = ary[j] ary[j] = ary[j+1]; ary[j+1] = temp; flag = true; } } if(!flag) { break; } } console.log(ary) } var ary = [8, 3, 1, 2, -1, 7]; bubbleSort(ary); In the above-given code, we created an array named ‘ary’ and assigned some data to it. Then we created a function named bubbleSort and we passed the array to it. A variable named ‘flag’ is initially assigned with a value ‘false’. Next, the for-loop is initialized with the 0 and it will execute until it is less than the array length. Nested for-loops are utilized to draw a comparison of the value at the current index with the value at the adjacent index, the values will be swapped only if the value of the current index is higher than the value present at its adjacent index. The value of the flag will be replaced with true if a value is swapped during iteration. Finally, the array is called using the bubbleSort function. The output will be:

 Conclusion

Bubble sort is a basic sorting algorithm that swaps the side-by-side elements over and over again until they are not in proper order. In this article, we presented all the basics and essential knowledge needed to understand the concept of bubble sort. Starting with the introduction that described what bubble sort is and how it works. Then we took an example to understand the concept of bubble sort. Furthermore, we implemented the same example and discussed its working in detail.

Understand Async/Await functions | Explained with Examples

The keyword async is used to convert a function into an async function while await keyword is only useable inside an async function. Async and await are used for asynchronous execution of the program and implement a promise-driven functionality to the code. Async keyword when used from defining a function makes the function return a Promise, while await function makes the async function wait for a promise to be returned inside it. To understand the usage of async and await functions you need to have a keen understanding of how promises work. Async and await is an advanced-level JavaScript concept, that is why we are going to learn it through various examples and understand it by going through the example line by line.

 Sequential Execution

JavaScript is a sequentially executed or we can say single-threaded scripting language. The code is invoked line by line in a procedural fashion. Consider the lines of code typed below: function hello() { console.log("Hello World"); linuxHint();}function linuxHint() { console.log("Tutorial by linuxHint");} console.log("Code is executed in the sequence that it is invoked"); hello(); Observe the output on the console as: As you can see, the functions or lines invoked first were always finished first. The reason for showing you a simple example like this was to make you notice when the execution sequence will change with async await and promises.

 Async/ Await in action

Consider a simple function that returns some text, like: function getUsers() { console.log("Inside the getUsers function"); return "Users";} console.log("Start of the code");var list = getUsers(); console.log(list); console.log("End of the code"); The output of the following code is: As we can see the function returned as the string that says, users. Let’s try putting the keyword async before function definition as: async function getUsers() { console.log("Inside the getUsers function"); return "Users";} Now, on your console you will see that this time around the function returned a promise that had the status “fulfilled”: But in cases where you are fetching some data from some REST API or any WEB API, this promise will change multiple states, from pending to fulfilled/rejected. In such cases, we wait for the return of the promise’s result by using the await keyword. For this, we are going to use the Fetch API and fetch the information about users from the “api.github/users” with the following lines of code: async function getUsers() { console.log("Inside the getUsers function"); const response = await fetch("https://api.github.com/users"); console.log("API RESPONDED, USERS RECEIVED"); const users = await response.json(); console.log("CONVERTED JSON"); return users;} There is a lot of stuff to be explained here: When a new variable is initialized with this function, the first line will be executed and text will be printed onto the console. When the code reaches the keyword await it will check whether the promise is fulfilled or pending, if it is in the pending state then it will exit this function and execute other parts of the code. After executing other parts of the code, it will come back inside the function at the first await keyword and recheck the status of the promise. Upon receiving a fulfilled/reject status it will execute the next line which is console.log(). In the next line, response.json is also a promise, it will check for its status and upon pending status, it will exit the function and execute the other parts of the code. After all the other code is executed, the pointer will come back in the function, check the status of response.json, and on fulfilled/rejected status it will execute the next line. In this way, this whole program will exit the normal sequential execution and implement an asynchronous execution of the code by using promises and async/await keywords. The complete code snippet is as: async function getUsers() { console.log("Inside the getUsers function"); const response = await fetch("https://api.github.com/users"); console.log("API RESPONDED, USERS RECEIVED"); const users = await response.json(); console.log("CONVERTED JSON"); return users;} console.log("Code starts");var list = getUsers(); console.log("Variable list created"); console.log(list); list.then((user) => console.log(user)); console.log("Last line of the code"); Note: The line “list.then((user) => console.log(user));” will not be executed until the function getUsers deals with all the promises and returns the value, even here the sequential execution will alter. Now, if you run this program as a script of an HTML file, you will see the following output on your console: Examine the output closely and you will notice the flow of execution as: Code starts and the variable is declared on the function. The pointer goes inside the function, prints the first line, sees the await keyword, leaves the function, and returns a pending promise to the variable “list” that we just created. Executes other parts of the code (that is why you can see “last line of the code”) while waiting for the promise in the await. Sees the line list.then() but it will not be executed until the function getUsers returns a promise with a status solved/rejected. Goes back inside the function, API responds, creates a list of users, and converts it into JSON. The status of the promises returned by the async function getUsers changes to fulfilled and the list.then() line executed and we get the JSON data printed onto the console. That is how you alter sequential execution and implement asynchronous execution

 Conclusion

Async and await keywords are used to implement asynchronous execution of the JavaScript code with the help of promises. Async keyword when used before the declaration of a function converts that function into an async function and its return type changes to a promise. While await is a keyword that waits for a promise to be received inside an async function. Async/await help us write promises in a much nicer, and tidy way that is more readable and understandable.

This, Bind, Call, and Apply | Explained

Bind, call and apply are really useful and special methods that help us achieve borrowing of features and methods from one object to another using the reference “this”. This is a little advanced topic, that is why we are going to take things slow for you and explain every minute detail with examples. JavaScript and many other programming languages use the keyword this to pass the reference of the parent object/class to its functions and methods inside them. While, the Bind, call and apply methods work on the passing of reference to borrow attributes from one object to another. The bind, call and apply feature was added in the ECMA2015 release.

 The “this” reference

The keyword this has a very specific meaning, it refers to the object who is calling the function. If we are working with a constructor method then the keyword this would refer to the class and its properties, if we are working with some DOM elements then this keyword would refer to the global values of the DOM. To demonstrate this, create the following object using the following lines: var person = { name: "John Doe", age: 25, designation: "Auditor", printName: function () { console.log(this.name); },}; As you can see, inside the object person we have a function printName which will print the name of the person, and inside the console.log() we can see that we have the line: this.name; This keyword is creating a reference to the object and tells the compiler to fetch the “name” from this particular object.

 Call and apply methods

Call and apply can both be defined simultaneously because they have almost exactly the same working mechanics. Call and apply are used for function borrowing, function borrowing means to use the function of some other object and use the reference of some other object. To understand this concept better, create two different objects using the following lines of code: var person1 = { name: "John Doe", age: 25, designation: "Auditor", printName: function () { console.log(this.name); },};var person2 = { name: "Baba Yaga", age: 22, designation: "Unemployed",}; As you can see in the code snippet, we have almost the same structure of both the objects and the same key-value pairs except for the fact that person1 has the function printName while person2 does not. But if you want to print out the “name” of the person2 object, you can do that by using the method “printName” from the person1 object, and for the “this” reference, you pass in the reference of the object person2.

 Syntax of call and apply:

The syntax of both these methods is almost identical: For call method the syntax is as: obj1.function.call(refferenceOfObject2,arg1 arg2,arg3...); For apply method the syntax is as: obj1.function.apply(refferenceOfObject2,[arg1,arg2,arg3,...]); Note: if the function that you are borrowing needs some additional arguments, then in the call method you pass in the arguments separated by a comma “, ” and in the case of the apply method, you pass additional arguments as an array list.

 Using call and apply methods

Coming back to our original problem, we can use the “printName” function from the “person1” object to print out the name of the person2 object using the following line of code: person1.printName.call(person2); If you run the above command you will see the following output: Similarly, you can use the apply() method for the same purpose using the of code: person1.printName.apply(person2); But what if the printName() function is taking in some arguments like: printName: function (city, siblings) { console.log(`${this.name} from ${city} has ${siblings} siblings`); }, For this case, you will use the call function with the following line of code: person1.printName.call(person2, "New York", 4); The complete code snippet is as: var person1 = { name: "John Doe", age: 25, designation: "Auditor", printName: function (city, siblings) { console.log(`${this.name} from ${city} has ${siblings} siblings`); },};var person2 = { name: "Baba Yaga", age: 22, designation: "Unemployed",}; person1.printName.call(person2, "New York", 4); If you execute the following code, you will get the output as: As you can see, you were able to pass the arguments using the call method, you can do this by using the apply() method as well by using the following code snippet: var person1 = { name: "John Doe", age: 25, designation: "Auditor", printName: function (city, siblings) { console.log(`${this.name} from ${city} has ${siblings} siblings`); },};var person2 = { name: "Baba Yaga", age: 22, designation: "Unemployed",}; person1.printName.apply(person2, ["New York", 4]); Note: for passing arguments to the borrowed function through the apply() method, we are using an array containing the arguments. If you execute this code you will get the same identical output as: But what if you don’t want to borrow a function from some object? This is where the bind method comes into play.

 The bind() method

Unlike the call and apply methods, bind methods are used to create a copy of a function and then place that copied function as an attribute of the object so that the function can be used at a later time.

 Syntax of the bind method

The syntax is as: var newFunctionName = object1.function.bind(refereceToObject2); Note: The bind method returns a function that is replicated. To demonstrate this, let’s alter the code from the above example in this way: var person1 = { firstName: "John", lastName: "Doe", age: 25, printFullName: function () { console.log(this.firstName + " " + this.lastName); },};var person2 = { firstName: "Baba", lastName: "Yaga", age: 25,}; Now if you want to make a copy of the function printFullName from the object person1 and make it an attribute of the object person2 then you can do that by using the following line of code: var printMyName = person1.printFullName.bind(person2); With this line, you have “binded” an attribute function printMyName with the object person2, and you can invoke it using the command: printMyName() Note: You are not calling it with the person2 object by using the dot-operate because the reference to the person2 object is already “binded” to the function. The complete code snippet is as: var person1 = { firstName: "John", lastName: "Doe", age: 25, printFullName: function () { console.log(this.firstName + " " + this.lastName); },};var person2 = { firstName: "Baba", lastName: "Yaga", age: 25,};var printMyName = person1.printFullName.bind(person2); printMyName(); When you execute this code snippet you get the following output: There you go, you have duplicated a function from person1 object, passed the reference of person2 object, and stored it as a separate function.

 Conclusion

Call, bind and apply methods are complicated methods that are used to play with the reference of the objects and help you to achieve feats like function borrowing and function replication with a different reference. To understand the details of these functions we need to know what the keyword this means and how referencing works in JS. You learned about the working of this, call, apply and bind methods along with their examples.

Maps | Explained

Maps are also a type of structured data storing similar to objects and arrays. However, Maps bring out the best of objects and arrays. Maps store data in key-value pairs much like an object with the difference being that the key in Maps can be of various data types. Map stores data in a preserved order, making it similar to an array with the difference being key-value pairs instead of indexed values. Maps were released in the ES6 version of JavaScript which is also known as the ES2015 Js. Maps are mostly used because they provide flexibility to the programmer.

 Syntax of Maps

To initialize a new map, you will use the following syntax: var map = new Map(); As you can see, we create a new Map by calling its constructor function by using the keyword “new”.

 How to work with Maps?

Let’s create a new map variable by using the following line: var dataSet = new Map(); You have created new dataSet in which you can store various types of information, to put values inside a map you use the set method. The syntax of the map’s set method is as: map.set( key ,"value") ; Now you know the syntax, so let’s try putting in some values inside the map with the following lines of code: dataSet.set(1, "English"); dataSet.set(2, "Spanish"); dataSet.set(3, "French"); As you can see, you have added three key-value pairs inside the map, you can verify it by printing out the map using the console.log() function like: console.log(dataSet); The whole code snippet is as var dataSet = new Map(); dataSet.set(1, "English"); dataSet.set(2, "Spanish"); dataSet.set(3, "French"); console.log(dataSet); After running this code, you will see the following output on your console: Note that there is an interesting thing inside the output that differentiates a map from an object, In Objects, key-value pairs are separated by a colon “:” while in the case of Maps, the key-value pairs are separated by an arrow “=>”.

 Iterating through a Map

You have multiple ways of iterating through the map, one of the traditional ways is to use the for-of map.

 Fetching Keys of the Map

You can iterate through the keys of the map by using the following lines of code: for (keys of dataSet.keys()) { console.log(`Keys are : ${keys}`);} The output is as

 Fetching Values of the Map

To iterate through the values of the map, you can use the following lines of code: for (Values of dataSet.values()) { console.log(`Values are : ${Values}`);} The output is as

 Fetching keys and values as a pair

if you want to get both keys and values as a pair, well you can do that by using the following lines of code: for ([keys, values] of dataSet) { console.log(`Key is : ${keys} and Value is : ${values}`);}

 Getting a specific value from a specific key

You can even get a specific value from a map using the get method, try the following line of code: console.log(dataSet.get(1)); You will get the following output: As you can see, you were able to get the value of a specific key using the get method.

 Various Types of Keys

As mentioned above, that a map can have various types of keys which is the main feature that differentiates a map from a simple object. Let’s take the same map that we have been using in all the above examples, but let’s add some key-value pairs, with different types of keys: String as a key You can have keys of string data types like showing in the following line: dataSet.set("Coms", "Pretty Good"); Boolean as a key You can have a key of boolean data types like the following line of code: dataSet.set(true, 1); dataSet.set(false,0); Objects as a key You can even pass objects as keys, try the following lines of code: var person1 = { Name: "John Doe", Age: 25, height: "6 ft 2" }; dataSet.set(person1, "Member"); To verify all of the above code, you can simply call a console.log() function to print out the map onto the console as: console.log(dataSet); The complete code snippet is as var dataSet = new Map(); dataSet.set(1, "English"); dataSet.set("Coms", "Pretty Good"); dataSet.set(true, 1); dataSet.set(false, 0); var person1 = { Name: "John Doe", Age: 25, height: "6 ft 2" }; dataSet.set(person1, "Member"); console.log(dataSet); After running the above code you get the following output: As you can see, every key was added into the dataSet along with its value, and that is how maps work.

 Conclusion

Maps are a collection of key-value pairs that are stored in a preserved order thus making the map mimic the behavior of both the object and an array. Maps can have any data type of key and any data type of value while maintaining the order of the key-value pairs just like in arrays. You can add key-value pairs inside the map using the set() method of the map, you can get a specific value using the get() method, and to iterate through the whole map you can use the for-of loop. Maps are used because they provide more flexibility and freedom to the programmer.

Event Loops | Explained with Examples

Event Loop is an advanced-level JavaScript concept, the Event loop is a function of javascript that places the instructions waiting in the event queue to the global execution stack. When you are working with asynchronous execution you have 3 different environments running which are namely: Execution stack, WEB APIs, and event/message queue which you can see in the image below: The global execution context maintains a stack of all the functions being executed, it works on the behavior “last in first out”. Whereas, the Web API environment picks up the functions which are part of Web API (API calls, AJAX call, setTimeout(), and more) from the execution stack and starts executing them in its own environment. This, in turn, allows the execution stack to work on something else, thus implementing an asynchronous behavior. When the WEB API finishes executing on the function it places the result onto the Event queue. Whenever the execution stack is empty, the event loop picks up the function in the event queue and places it back into the execution stack. This whole circle is known as the Event Loops. Try this simple sequential code: function f2() { console.log("Inside function F2"); console.log("F2 has finished");}function f1() { console.log("Inside Function F1"); f2(); console.log("Ending of Function F1");} f1(); The output of this code is as This code looks like this on the execution stack: The stack works in this order: Pointers goes in f1, and executes the command to print “inside function F1” and removes it from the stack Pointer sees the line f2() and goes inside the f2 Pointer executes “Inside function F2” and removes it from the stack Prints the lines “F2 has finished working” and removes it from the stack Since f2 is done, it removed the “f2();” from the stack and returns to f1 to execute the remaining part of the f1 function Prints the line “Ending of function F1” and removes it from the stack Since no command is left in f1(), the pointer removes it from the stack as well. Now, that you know how the execution stack works, you can move on to async code example by testing out the following lines of code: function f2() { console.log("Inside function F2"); setTimeout(() => { console.log("F2 has finished"); }, 3000);}function f1() { console.log("Inside Function F1"); f2(); console.log("Ending of Function F1");} f1(); As you can see, in function f2() we are now doing a task that takes 3 seconds to finish. When the pointer reaches this setTimeout() statement, it places it inside the Web APIs environment and removes it from the execution stack. The execution stack will keep working on the other part of the code while the WEB API will wait for the setTimeout() to finish like: After this setTimeout() instruction has been moved to the Web API environment, the execution stack will look like this: As you can see, while the Web API is working on the setTimeout function, the execution stack is working on other instructions and removing them from the stack. When the Web API finishes working on the “setTimeout()” it will move it to the event queue, while the Event loops wait for the execution stack to become empty. When the stack is empty, the Event loop will move the setTimeout result to the execution stack as: And then: This is how the event loop works, that is why you get the following output on your console: With the above output, you can verify the execution of the event loop

 Conclusion

The event loop is a function that moves the instructions waiting to be executed into the global execution stack from the event queue. Whenever a function like setTimeout() needs to be executed simultaneously it is moved from the execution stack to the Web API environment. Web API works on the instruction while the JavaScript continues to execute other parts of the code, once the Web API is done working on the instruction, it places the instruction or function in the event queue from where it is moved to the execution stack whenever the stack is empty. This whole cycle is known as the Event Loop.

Callbacks and Promises | Explained with Examples

JavaScript is a high-level programming language that executes synchronously which means code is executed line by line. The next lines of code cannot execute once the previous line of code is fully executed. However, we can also implement asynchronous code in which some block of code can be executed along with the original code thread so that execution of the code can be done in parallel. To implement asynchronous code we use callbacks and promises in JavaScript. In this post, we will see what are callbacks and promises explained with the help of examples.

 What are callbacks?

Callbacks are functions that are passed inside the arguments of other functions, this procedure is valid because functions are objects and objects can be passed as arguments to functions. The basic structure of the callback function looks something like this. function demoFunction(callback){ callback();}

 Execution sequence and need for callbacks

Callbacks functions are used to acquire control over the sequence of execution. Generally, functions are executed on the basis of the sequence that they are invoked, not on the sequence in which they are defined. For example: function job1() { console.log("I am task 1");}function job3() { console.log("I am task 3");}function job2() { console.log("I am task 2");} job1(); job2(); job3(); You would get the following output: But what if we want to invoke task 2 only when task 1 finishes its processing. For that, we need callback functions and some basic understanding of asynchronous execution.

 An example of callback in action

Consider the following code: var members = ["John Doe", "Sam Smith", "Allie Cartel"];function addNewMember(newUser) { members.push(newUser);}function getAllMembers() { console.log(members);} addNewMember("Alpha"); getAllMembers(); We are working with an array that contains the list of members of a social club, and we have two functions. One function that prints out the list of all the members and the other one is used to add a member to the list. Let’s change this code to make it mimic the behaviour of real databases and networking delays like lag and pings. var members = ["John Doe", "Sam Smith", "Allie Cartel"];function addNewMember(newUser) { setTimeout(function () { members.push(newUser); console.log("Member Added"); }, 200);}function getAllMembers() { setTimeout(function () { console.log("Members are:"); console.log(members); }, 100);} addNewMember("Alpha"); getAllMembers(); As you can see, this code is using the setTimeout() function to mimic delays of databases. The addUser takes about 2 seconds and getAllMembers() function takes 1 second. We want to add a new user “Alpha” and print the list after the member is added, not before and that is why we use the sequence: addNewMember("Alpha"); getAllMembers(); Run the code and you will get the following output: The list was printed first, and then the member was added. This is because the program did not wait for the addMember() function to finish processing. Now if we use callback functions to execute the getAllMembers() function only after the addNewMember() is finished, our code becomes: var members = ["John Doe", "Sam Smith", "Allie Cartel"];function addNewMember(newUser, callback) { setTimeout(function () { members.push(newUser); console.log("Member Added"); callback(); }, 200);}function getAllMembers() { setTimeout(function () { console.log("Members are:"); console.log(members); }, 100);} addNewMember("Alpha", getAllMembers); If you look at the code, you will see that inside the addNewMember() function we are taking a callback argument, this will ensure that the callback function will be executed in our desired sequence. The output of the above code snippet is as: The new member was added first and then the whole list was printed onto the console. That is how you can use callbacks to gain control of the sequence of execution.

 What are promises?

A promise is an object and is something that is done/completed in the future., it is exactly the same as in real life. The syntax of a promise is given below: var myPromise = new Promise(function(resolve, reject){ // some code}); As can be seen from the Promise syntax, the promise constructor only accepts the callback function as an argument. The resolve and reject parameters are used in the callback function, with resolve being called when the activities conducted inside the callback function are successful. If the procedure is unsuccessful, however, rejection is called. For example, let’s suppose your mother promises you to get you a bicycle on your birthday. That promise is her guarantee that she will buy you a bicycle on your birthday however when the time comes she can change her mind. So she can buy you a bicycle or not. This is a promise in simple layman language. Looking at this example we can identify three states/ possibilities of a promise: Fulfilled: bicycle is bought. Result value Pending: your birthday has not come and you are not sure whether your mother will buy you a bicycle or not. Undefined Rejected: Bicycles are not bought for you on your birthday. Error. To better understand Promises let us go through an example: We will take this example step by step i-e first we will create a promise object using the Promise constructor as seen in the syntax of promise above. Next, we will use that promise object. In the below code we will create a promise object: // creating Promise objectvar myPromise = new Promise(function(resolve, reject) { const number1 = 2; const number2 = 2; // comparing two numbers if(number1 === number2) { // Operation successful resolve(); } else { // Error occurred reject(); }}); In the above code, first, we created a promise object myPromise, and then passed a callback function inside the Promise constructor. In the function, we are checking whether two numbers are equal or not. If the numbers are equal, the call will be resolved, otherwise if an error comes then the call will be rejected. To use the promise object (myPromise) we will need “promise consumers” (consume Promises by registering functions) known as then() method for fulfilment and catch() method for rejection. The below code illustrates this: myPromise.then(function () { console.log("Numbers Equal. Success");}).catch(function () { console.log('Error');}); If the numbers that are being checked are equal then the .then() method will be invoked and we will see “Numbers Equal. Success”. However, if the numbers are not equal then the .catch() method will be invoked and we will see the Error message in the console window. The whole code is given below: // creating Promise objectvar myPromise = new Promise(function(resolve, reject) { const number1 = 2; const number2 = 2; // comparing two numbers if(number1 === number2) { // Operation successful resolve(); } else { // Error occurred reject(); }});// Use Promise object myPromise.then(function () { console.log("Numbers Equal. Success");}).catch(function () { console.log('Error');}); From the output, we can see that the numbers are equal.

 Conclusion

To implement asynchronous code we use callback functions and promises. A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future., a promise is an object and we use the promise constructor to initialize a promise. To use promise objects we take help from promise consumers that are then() method(if promise fulfilled) and catch() method (if promise is rejected).

ArrayBuffer | Explained

In this post, we will discuss what the ArrayBuffer object is along with examples.

 What is ArrayBuffer?

An array of bytes is known as an array buffer while known as a “byte array” in some other languages. The ArrayBuffer object represents a fixed-length raw binary data buffer whose content can’t be altered directly. A DataView object can also be used to access it, which is an untyped super flexible view over an ArrayBuffer or any typed array object that consists of regular array methods like map, find slice, etc. the content is read and written using these objects. Any modifications to one object of the ArrayBuffer will be visible to the other objects and only one DataView or typed array object must be included in a single Array Buffer.

 Syntax of ArrayBuffer

The Syntax of ArrayBuffer is given below: new ArrayBuffer(byteLength); The byteLength is a compulsory argument and it denotes the length or size of the array buffer in bytes that is being created. Note: The return value will be the new ArrayBuffer object with size byteLength. To further grasp the concept of an ArrayBuffer object, let us go through an example.

 Example 1

In this example, we will simply initialize the ArrayBuffer object and give the size 16 and then console log the length of the initialized buffer using the built-in method of the Array/buffer object byteLength: // initialize buffer with length 16var myBuffer = new ArrayBuffer(16);// console log the length of myBuffer console.log(myBuffer.byteLength); // 16

 Example 2

Let us manipulate the ArrayBuffer object a little further by using DataView. As discussed earlier we cannot modify or perform any operation on ArrayObject unless we use a view: // initialize ArrayBuffer object with size 16var myBuffer = new ArrayBuffer(16);// DataView that refers to myBuffer objectvar view1 = new DataView(myBuffer);// Int8Array that refers to myBuffer objectvar view2 = new Int8Array(myBuffer);// set value to 32 bits view1.setInt32(0, 0x76543210);// console log the 32 bit value console.log("32 bit value: "+view1.getInt32(0).toString(16));// console log only the 8 bit value console.log("8 bit value: "+view1.getInt8(0).toString(16)); console.log("32 bit value: "+view2[0].toString(16)); In the code above, first, we initialized an ArrayBuffer object with size 16 and then we referred to that ArrayObject with a DataView. We repeated the process of initializing another view using the Int8Array which represents the two’s-complement 8 bit signed integer array. After that we set the first view value to 32 bits and the second view value to 8-bit value and then console log it:

 Conclusion

One of the core objects is the ArrayBuffer object, which is a fixed-length contiguous memory space reference whose content cannot be altered directly; instead, we need a Typed Array or a Data View. Data View specifies a format using methods, for example, getUint8(offset). To put it simply, an ArrayBuffer is used to store binary data, for example, binary data of a file or image. In this post, we discussed the ArrayBuffer object along with two examples in which the first we simply initialized the ArrayBuffer object, and in the second example, we manipulated the ArrayBuffer object.

How to remove a class name from an element through JavaScript

As we are aware of the fact that JavaScript is commonly used to manipulate the elements of an HTML page with the help of the DOM node interface. These manipulations can not only change the style or data inside the HTML elements but they can even change the attributes of the elements such as the class names. Changing or removing a class name from an element is a crucial job especially when you are working with styling animation on elements. To shift an animation from one element to another element you don’t rewrite the entire animation script of the other elements as that can increase the load on the server rather you write animation script on class names or IDs, and for shifting you simply change or remove the class name or the ID of an HTML element of the webpage. To remove the class name from an element we use the .classList.remove() function. The Syntax is: element.classList.remove( classname ) We are going to learn how we can use JavaScript to remove a class name from an element on the web page. For this, we are going to create: A basic HTML page with an element having a class name that we want to remove. A button that will invoke the function. The function linked to the button will actually remove the class name. The browser’s developer tools to verify the removal of the class name. Let’s get started.

 Setting up the HTML page

We are going to create a <div>element with a list of various class names. This <div>will also have a specific ID to create a reference to this <div>when we are using JavaScript. We can create this by using the following lines: <center> <div class="google yahoo bing LinuxHint" id="LH-Tuts" style="background-color: cadetblue"> This is a div with multiple classes </div></center> We have a div with the classes “google yahoo bing LinuxHint” and the id is “LH-Tuts. We added the style property to make it visible. We run the HTML file to get the following output: Now that we have a basic HTML page, let’s create a button that will remove a class from the <div>element. We do that by using the following lines of code: <button onclick="removeClass()">Remove Class</button> Our webpage will look like this:

 Creating the JavaScript code to remove the class from the element

Now we have to write a function “removeClass()” in the script. So let’s create a <script>tag and write a function that will remove the class “google” from the list of classes with the following lines: <script> function removeClass() { div = document.getElementById("LH-Tuts"); div.classList.remove("google"); } </script> This function should remove the class “google” from the list of classes of the <div>element. Let’s try it out and verify the output with the browser’s developer tools. As you can see, at first the div has 4 different classes. But as soon as we press the button, the “google” class name gets removed from the list of the class names. We can even remove multiple classes at the same time, for that we use the line: div.classList.remove("google", "yahoo", "bing"); The function snippet would become: <script> function removeClass() { div = document.getElementById("LH-Tuts"); div.classList.remove("google", "yahoo", "bing"); }</script> Now, if we examine the output with the browser’s developer tools, we get: As you can see, we were able to remove multiple classes at the same time as well.

 Alternate Approach

There is one more thing, we were using the document.getElementByID() to create a reference to the element, we can even use the document.getElementByClassName(), but for that we will have to change our script. As we cannot refer to an element using its class name and then delete a class name while maintaining a reference to the element. That is because the className is a “LIVE NODELIST”. To use document.getElementsByClassName() our function becomes: function removeClass() { div = document.getElementsByClassName("google yahoo bing LinuxHint"); while (div.length) { div[0].classList.remove("yahoo", "bing"); } } Since it is a Live nodeList, we take the first item in the list and remove its class name. We keep repeating this until the NodeList is empty. The output is as: That is it for removing a class name from an element using JavaScript.

 Conclusion

JavaScript can be used to remove a class name from an HTML element on a webpage with the help of the .classList.remove(). It can even be used to remove multiple classes from the class list of an element. To showcase this, we created a basic HTML with a div element on it. Afterward, we coded a script to remove the class from that element. We examined the output using the browser’s developer tools and we even tried out an alternative way of doing the same task.

How To Install the Deno JavaScript Runtime on Ubuntu 20.04

Deno JavaScript is the newest product from the creator of NodeJs, and just like the NodeJs, Deno is also a runtime JavaScript working on V8 JavaScript, created for being secure from the start and supports typescript. In this post today, you are going to learn how to install DenoJavaScript on the Linux distribution Ubuntu 20.04. We are going to update our packages, download Deno, install Deno and verify the installation of Deno JavaScript.

 Step 1: Update Ubuntu and Packages

To install Deno JavaScript on Ubuntu 20.4 is to make sure that we are running the latest version of Ubuntu and we have all the packages up-to-date. We can do that by using the following commands in Ubuntu: $ sudo apt update -y $ sudo apt upgrade -y

 Step 2: Installing Unzip

The next step is to make sure that we have an unzipper on our machine, this is because the file that we are going to download to our machine is a zipped file; to install unzip utility you can use the following command: $ sudo apt install unzip You can see it in the image below:

 Step 3: Downloading Deno.zip

Now that you have updated your system and installed an unzipper in your machine, we need to download deno.zip, for that head inside the folder in which you want to download the file using the following command: $ cd /tmp Now, to download Deno use the following command $ curl -Lo "deno.zip" "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-unknown-linux-gnu.zip" This command would start downloading the deno.zip from its Github, after executing the command you should see a progress bar like: If curl is not installed then install it using the command provided below: $ sudo apt install curl

 Step 4: Installing Deno

After downloading Deno, we need to unzip it inside a folder with the following command: $ sudo unzip -d /usr/local/bin /tmp/deno.zip This above command will unzip/install the Deno javascript in the /usr/local/bin folder, the next thing we need to do is to make sure the root and owner permission is correct, to verify that use the following command: $ ls -al /usr/local/bin/deno You should see the following output on the terminal:

 Step 5: Verifying Installation

To verify the installation of Deno JavaScript you can use the following command to check the version of the Deno JavaScript. $ deno --version You should see the following output:

 Step 6: Testing DenoJs

In order to use Deno and execute a basic Hello World we are going to use the Deno REPL with the following command: $ deno And then we use the following command: ['hello', 'world'].join(' ') You will see the below-mentioned output on your screen: That is it, you have installed Deno JavaScript on Ubuntu 20.04

 Conclusion

Deno JavaScript can be installed by downloading “deno.zip” from their official Github Repository and extracting it in your desired directory. Following this step-by-step guide, you have learned how to install the Deno JavaScript on Ubuntu 20.04 and even tested a simple hello world program using Deno REPL. Deno is a runtime JavaScript which is running on V8 JavaScript.

How to format numbers using the toFixed() method

JavaScript is a high-level programming language that is used to make our web application and web pages interactive by giving them the ability to perform certain actions on the basis of some triggers. Triggers can be any event predefined by the developer, it can be the press of a specific button on the web page or a particular mouse location. Like any other language, JavaScript offers us built-in methods which are a set or collection of statements that perform some specific function. Built-in methods are very helpful as they make our code cleaner and save us time. We don’t have to write the whole functionality ourselves, instead, it’s given to us, and we just call that method when we require that specific functionality. One such built-in method is the toFixed() method. In this post, we’ll explore how to format numbers using the toFixed() method and to get started let us see what is toFixed() method and how to use it.

 How to use toFixed() method

The toFixed() method was introduced in ES3 and is a built-in number method that rounds off a number to some specific number of decimals and returns that number as a string. As it is a number class built-in method hence it can only be called with a number datatype. The syntax for the toFixed() method is: myNum.toFixed(number); The toFixed() method takes the number as an argument which is used to specify the number of decimals one needs rounding off. It is an optional argument and if you don’t pass it to the toFixed() method then by default toFixed() method will take 0 in place of the number and a string will be returned with no digits after the decimal point. Now that we know what is the toFixed() method, let us format numbers using examples:

 Example 1

Let us go through a simple example where first we will initialize a variable with a number and then call the toFixed() method on that number by displaying the returned string in the console log: var myNum = 19.5678; // declare number console.log(myNum.toFixed(2)); // 19.57 We will see that the myNum will round off to 19.57 as we have passed 2 as an argument to the toFixed() method:

 Example 2

In this example, we will test the default behaviour of toFixed() method by not passing any argument to the toFixed() method: var myNum = 19.5678; // declare number console.log(myNum.toFixed()); // 19 We will see that the number is returned as a string and is round off but without any decimals:

 Example 3

Now let’s see another case where suppose you pass 10 as an argument to the toFixed() method but the number you are calling the method on does not have this many decimal places and has fewer decimal places than 10. var myNum = 19.5678; // declare number console.log(myNum.toFixed(10)); // 19.5678000000 In this case, we will see that the toFixed() method adds extra 0s to the output hence returning a string that has 10 decimal places:

 Conclusion

The toFixed() method was introduced in ECMAScript 3 and is used with a number class that returns a string rounded off with the specified number of digits present after the decimal point. The toFixed() method is supported by all the major browsers available for example, Google Chrome, Mozilla Firefox, Microsoft Edge, etc. In this post, first, we discussed what the toFixed() method is and then we went on to describe its syntax as well as give examples of formatting numbers using the toFixed() method.

How to Dynamically Import JavaScript with Import Maps

Dynamic importing is the process of importing external libraries only when they are required, thus creating less congestion on the server. Dynamic importing is an exceptionally useful feature that greatly affects the optimization of a web application by reducing the loading time and reducing the memory required on the server. Dynamic Import in web pages is done through a feature called import maps. You are going to learn about dynamic load, default build tool behavior, and the use of import maps with a step-by-step example. Let’s get started.

 Default Build Tool Behaviour

By default, when you run an HTML webpage and all the scripts which are included inside it are compiled inside one big file. All the external and internal libraries are instantly loaded into the memory(server) and a lot of complexity is added to the project because of loading various external code snippets at the same time. Previously, JavaScript applications were very simple and basic, but as time passes, the applications are becoming more and more challenging and complex, and that is exactly why loading all the external libraries at the same time even before they are needed is not an efficient solution. That is where dynamic loading and modularity of scripts come in handy.

 Dynamic Loading

As the name indicates, it is the process of loading external libraries and scripts only when they are needed, that is at run time. As far as the script of the web application is concerned, dynamic script loading is done by a feature in ES6 called modules in which scripts are divided into smaller components. Similarly, importing is also done at run time using import maps. To load imports at run time we use a feature called import maps, this feature allows us to override the default procedure of the build tools and lazy load our imports/libraries; lazy loading means to load only when it is required. To demonstrate dynamically importing external scripts in a Web page, you are going to set up a webpage that performs a simple task, Afterwards, we are going to import an external library/package lodash and use its function to perform the same task Note: You need a code editor (preferably Vs Code) for this and NodeJs,

 Step 1: Setting Up an HTML and a Script file

To demonstrate the use of import maps for dynamic loading we will require NodeJs to be installed on our system, Click here to read the installation of NodeJS. Create a folder on your machine and open that folder with VS Code (or your desired code editor) as shown below: Inside the folder, create an HTML file named home.html and a script file as script.js: We are going to display some words by using the script file. So, in the HTML file add the following script tag. <script type="module" src="script.js"></script> Note: we are using the type property and setting it equal to module to notify the browser that this is a modular script. Now, inside the script file, type in the following lines of code to print text to the HTML web page. const el = document.createElement(`p`);const words = "Linux, Hint, Tutorial!";const text = document.createTextNode(words); el.appendChild(text); document.body.appendChild(el); To run the file, open the terminal of the VS Code and type “npx serve”, if it is your first time trying the npx serve command then it might install the “serve” package and ask for affirmation, and then it will start the installation: After that, the npx serve command will show us where is it hosting our HTML webpage, so click on the link as follows: When you open the link http://localhost:3000 you would see the following output:

 Step 2: Importing external Library

We are going to import startCase method from the lodash library and use this startCase method to convert our strings in to “start the case” type using the following code: import startCase from '@lodash/startCase'; Note: start the case type means every word will have the first letter in a capital case. You are going to modify the script file as: import startCase from "@lodash/startCase";const el = document.createElement("p");const toDisplay = "linux, hint, tutorial!";const text = document.createTextNode(startCase(toDisplay)); el.appendChild(text); document.body.appendChild(el); As you can see, the code is a little different, we are passing the ToDisplay variable to the startCase function. Refresh the page and you will see the following error on your developer console: This is because the browser doesn’t know what to do with this import statement at the start of the script file. The browser is trying to find the lodash package on the local web server, this is also the default behavior of the build tool. To change this we use import maps in HTML files.

 Step 3: Using import maps

Import map, is an ES6 feature, it contains a key-value pair, with the key being the name of the import and the value being the location of the import. The syntax of the import map is: <script type="importmap">{ "imports": { "nameOfImport": "locationOfCode", "nameOfSecondImport": "secondLocation" }}</script> For our case, we add the following script tag including the import map: <script type="importmap"> { "imports": { "@lodash/startCase": "https://unpkg.com/lodash-es@4.17.21/startCase.js" } } </script> Note: The script tag containing the import map must be added before the script tag containing the modular type. After adding these lines, refresh your web page and you should see the output: As you can see, the startCase method successfully converted our string words in to “start the case” type. You are now including external libraries dynamically and we can examine the lazy loading in the developer tools of the browser.

 Step 4: Examine Lazy Loading

Open the browser’s developer console and head over to the network tab. Under the waterfall, you can see which script was loading at what time: And from here you can clearly see that all of the scripts were not loaded at the start, they were loaded lazily meaning at run time.

 Conclusion

In JavaScript, dynamic importing is done by a feature called Import Maps. Dynamic Import means to override the default behavior of the build tools and import external libraries when they are needed at run time because sometimes you need a library on only one part of your web application and not the others. Default build tools will load all the libraries in one big file which will cause an increase in memory consumption. You have learned how to use the import maps to lazy load external libraries with an example and examined it in the developer’s console.

What is spread (…) syntax | Explained with Examples

The spread operator is used to expand an array instance or a string instance over a list of arguments as individual elements, the arguments can also be zero or less than the length of the iterable array/string. JavaScript released a lot of features with the release of the ES6 JavaScript back in 2015, one of the features that were new to JavaScript was the spread operator; the spread Operator has a similar identifier to the rest parameters which is the triple-dot “…” before the variable name.

 The Spread Operator (…)

The triple-dot identifier when used before a variable name in an argument is known as the spread syntax or a spread argument. The spread argument breaks the iterable object (array or a string) and passes them on to the arguments. Syntax (...variableName) To understand the difference between normal variable output and the spread variable out, take a look at the figure below:

 How spread works with console.log()

To understand the basic functionality of the spread operator, you are simply going to create a string object and pass it inside the console.log() function. Afterward, use the spread operator to pass it inside the console.log() to examine the behavior of the spread operator: string = "GOOGLE"; console.log("Normal Syntax result: "+ string) console.log("Spread syntax result: "); console.log(...string); You will get the following output when you execute the code snippet above: The arrow is pointing at the normal string output and the red rectangle is enclosing the output of the spread syntax. You can notice gaps between each character of the spread syntax output that is because each character is being treated as a different element.

 Passing spread syntax in arguments of a function

The whole purpose of the spread syntax and the spread operator is to create the spread arguments and pass them inside the function. To demonstrate this you are going to create a function that will take 5 arguments and will print the result of the values passed inside the arguments with the following lines of code: function printSum(a,b,c,d,e){ console.log(a+b+c+d+e);} You are going to create an array with 5 integer values inside it using the following line: numbers = [1,2,3,4,5]; For the last step, you are going to call this function using the spread arguments and pass in the numbers array using the spread syntax like a single argument with the following line: printSum(...numbers); The complete snippet would be: function printSum(a, b, c, d, e) { console.log(a + b + c + d + e);} numbers = [1, 2, 3, 4, 5, 6]; printSum(...numbers); After executing the code, you will get the following output: All the elements inside the numbers array were passed as individual arguments to the function and then each argument was added printed on the console. But, What if your numbers array has more elements than the arguments of the function?; Well, in that case, only the first 5 elements of the array will be used and others will be discarded, thus, preventing any error. To showcase this, take the above-mentioned function and pass in the following array inside it: Array: Numbers = [3,52,6,7,1,3,5,3,1,5,3,6,7,3,5,6,1,2]; By using the following command: printSum(...Numbers); You will see the following result on the console: You can see, even though we had more elements inside the array that were passed into the argument’s list with the spread syntax, the extra elements were all discarded, and therefore, we did not get any errors.

 How to concatenate arrays using spread?

We can even use the spread syntax or the spread operator to concatenate array elements with other elements by passing in the complete array within a single element. array1 = [2, 3, 4, 5, 6, 6, 7, 7]; array2 = [1, 10, 2, 44, 66, 22, 11, 33, 56]; finalArray = [...array1, ...array2]; console.log(finalArray); You will get the following output: You can see that the finallArray has both the array1 and array2 concatenated inside it and we only gave two elements in the “finalArray”. That is for the spread syntax.

 Conclusion

Spread syntax was introduced as a new feature with the release of ES6. Spread syntax or commonly known as the spread argument is used to expand the elements of an iterable object -: Array or String – over a list of arguments of a function by individually passing each element. This functionality of the ES6 JavaScript programming language allows dealing with certain scenarios where you have more arguments than the parameters of the function. The spread operator can also be used to concatenate elements of the array which we examined with the help of an example.

Generators | Explained with Examples

Generators are functions that are used to get multiple values at various times. Generators are a bit complex to understand so we are going to define what generators are in simple words and then go into detail about generators and their working. JavaScript often comes up with solutions for various problems especially with the arrival of the ES6 version of JavaScript. One of the key features that were introduced in ES6 was Generators, Generators are used with iterators to create a flow of data or a stream of data. Generators help us avoid callback function issues.

 What actually are generators

In simple words, Generators are special functions; unlike normal functions that only have one return statement, Generators return multiple values but at different times. To be more descriptive, generators are functions that return value mid-way through the function and then stop executing after saving the state, this step of returning a value, saving state, and halting execution is called yielding a value and pausing. During this pause, the program can work on some other functionality, and then when we are required, the generator is asked to return the next value, but rather than restarting the whole function, the generator runs from the point where it stopped and yields the next value. Thus, creating a constant stream of data. That is why these functions are called “Generators” as they are used to generate the stream of data. We can look at the following working diagrams to better understand the difference between normal and generator functions: And generator function work like this:

 How to define a Generator function?

Since generator functions are special functions that is why we use a special keyword while defining them that is “function*” – asterisk after the function keyword. The syntax is as: function* functionName (params) {// body of the function yield value;} ‘ Note: Function*: keyword for defining generator functions functionName: The identifier for this function Params: Optional parameters that you want to use Yield: Returns value and halts the execution of the function Return value: Object [ Generator ] – A generator Object OR undefined if generator is empty We are now familiar with what a generator function is, but we are still not familiar with its return type that is the “Generator Object”.

 What is a generator object?

When a generator function is created it returns an object that we must initialize in some variable, this variable is then known as the Generator Object. This generator object is used to get the next value from the function. Syntax of initializing a generator object variable = generatorFunctionName( arguments ); After you have created the generator object you can use the function “object.next()” The object.next() returns a JSON object with two properties, one is the “value” and the other is the “done” property.

 Getting Values from a generator function

Let’s create a simple generator function that will return us a new value every time it is called, with the following lines of code: function* generator() { yield 1; yield "FOUND"; yield 3;} Now that we have a generator we need to initialize it with a generator object, we do that with the following statement: const genObject = generator(); Now we have the generator object as well. All we have to do now is to call the next() function of the generator object and print the JSON object with the console.log() function. console.log(genObject.next()); console.log(genObject.next()); console.log(genObject.next()); The complete code snippet looks like this: function* generator() { yield 1; yield "FOUND"; yield 3;}const genObject = generator(); console.log(genObject.next()); console.log(genObject.next()); console.log(genObject.next()); We get the following output: As you can see, we have printed 3 different JSON objects with 3 different calls to the same generator function. But, sometimes we want to use the value, not the JSON object. We can do that by accessing the value property of the JSON object with the following line of code: console.log(genObject.next().value); console.log(genObject.next().value); console.log(genObject.next().value); With these lines, we get the following output: As you can see, the object.next().value returns us a value which we can even pass onto some other function.

 Working of generator function in simultaneous code execution

For this tutorial, let’s create a simple generator function that will yield numbers from 1 to 5 and after every number that we fetch from the generator, our program will alert us that it is doing some calculations on that number and has left the generator function. The first step is to create a generator function that will yield 5 different numbers on 5 different calls with the following lines of code: function* generator() { console.log("Generator Function Initialized");for (let i = 1; i <= 5; i++) { console.log("Inside Generator for new yield"); yield i;}} As you can see, we have created a loop that will return 1 new integer on every generator yield call and prompt us whenever the program is inside the generator function. Now, we need to initialize this generator function with the generator object with the following line of code. const genObject = generator(); Now, we need a function that will do some work on the yielded values, create the function using the following lines: function tablePrinter(num) { console.log(`Currently Printing the Table of : ` + num);} We have a generator function, a generator object, and a function that will work on some values that are passed inside it. Now, all we need is an iterator that will iterate through the generator object and pass the values to the function. We do that by using the following lines of code: yieldedValue = genObject.next().value;while (yieldedValue) { tablePrinter(yieldedValue); yieldedValue = genObject.next().value;} What this code will do is that it will take the next value from the generator and store it inside a variable. Then in the while loop, it will check if the variable is undefined or not, and if it is not undefined then it will pass this value to the function “tablePrinter” and move on to the next value. The complete code snippet is as: function* generator() { console.log("Generator Function Initialized");for (let i = 1; i <= 5; i++) { console.log("Inside Generator for new yield"); yield i;}}const genObject = generator(); function tablePrinter(num) { console.log(`Currently Printing the Table of : ` + num);} yieldedValue = genObject.next().value;while (yieldedValue) { tablePrinter(yieldedValue); yieldedValue = genObject.next().value;} The output of the following code is: As you can see, the program goes inside the generator function and yields a new value, saves states, pauses the execution of the function, goes inside the “tablePrinter” function, and performs execution there. Once done it goes back inside the generator function for a new yield. This whole process is repeated until the generator keeps producing new yields. Thus, making it a Stream of data. That’s it for Generators.

 Conclusion

Generators are special functions that can halt their execution mid-way to yield a value, save their state and allow the program to perform other tasks. When needed the generator function “resumes” their execution from the state that they paused in. Generators are used to generate a constant stream of data. They are used in collaboration with promises and iterators to create an infinite stream of data and to avoid callback function issues.

Functions | Explained for beginners

JavaScript, like any other programming language, offers us functions that are very helpful as functions give us the ability to reuse our code and the code becomes clean i-e less congested with the implementation of modularity. If you are a beginner, don’t worry as in this post, we will hold your hand and walk you step by step to make you master functions.

 What is a function

A function is a collection of statements or commands wrapped in a block, kept and maintained separately from the main program to perform some specific task. Functions are very helpful as a developer can reuse that code again and again without needing to write the whole code again. Now that we know what a function is, let us go through the syntax of a function: function functionName(arguments) {// some statements or codereturn;} A function is declared with the keyword function followed by the name of the function which should be unique and it is a good practice to follow camelCase naming convention; the first word will be in lowercase and the words after that should have the first letter capitalized e.g myFunctionName. Right after the name comes the parenthesis () where parameters are received. We write the function code inside the curly brackets which comes after the parenthesis (). However, it should be noted that when you are working with classes then functions are defined without the keyword function. We open and close the function with curly brackets {} and all the code goes inside these curly brackets. The function takes input as an argument and returns the output via the keyword return. By default, a function returns undefined if there is nothing to return.

 Declaring and calling function

Let’s declare a proper function that will show an alert of Hello! function myFunc() { alert("Hello!")} Now that we have declared the functions with the name of myFunc let us call the function which can be done by writing the name of the function followed by (): function myFunc() { alert("Hello!")}// call function myFunc(); We will see the following output on our browser:

 Example 1

Now that we know how to declare and call a function, let us play with the arguments of the function. In this example, we will provide two arguments to the function and display their sum: function myFunc(num1, num2) { console.log(num1+num2);}// call function myFunc(2,3); // 5 myFunc(5,5); // 10 In the above code, first, we declared a function and the respective function is receiving two paramters. Next, we console log by adding both numbers. Outside the function, we invoked myFunc twice by providing different arguments. The result of the output is given below:

 Example 2

In this example, we will change the above code a little bit by providing default values to the parameters which mean if no value was provided when the function was invoked then the default value will be processed. We will also return the sum in this example: function myFunc(num1=1, num2=1) {return num1+num2;}// call function var sum=myFunc(); console.log(sum); // 2 The returned value is stored in the variable sum and we console log the value of the sum variable. As we didn’t provide any values when we invoked the myFunc function hence the function will process the default values which were 1 and 1 whose sum will be 2:

 Conclusion

A function is a set of statements put together under a specific name inside curly braces that is executed once we call the function name with round brackets. A function may take multiple arguments as input and return an output. A function helps in reusing the same code as well as it improves debugging and makes our code look clean by helping us implement the concept of modularity(a specific task is inside one block). In this post, first, we described what a function is and what its syntax is. Then we declared and called the function. After that, we provided examples to fully grasp the concept of functions.

For, For…Of, and For…In Loops | Explained

In programming languages, Loops are most used to repeatedly execute a block or chunk of code for a set amount of times or until a specific condition is met. JavaScript is no different when it comes to loops. The traditional loops that are used in other programming languages are For, while, and do while which are all present as well but with the arrival of ES6 a few modified versions of For loops were introduced. These were “For…of” and “For…in” loops. We are going to cover For loop, For-in loop, and For-of loop in detail.

 For Loop

The most common and the most widely used loop and probably in all other programming languages as well is the For loop. As we have already explained, these loops are used to repeatedly execute or invoke a chunk of code until a specific condition is met. This condition is passed inside the second parameter of the For loop. For loop is commonly used when we have a rough estimate of how many times will the loop run. Based on that we set our condition.

 Syntax of For loop

for ( initialize-variable ; condition-to-be-met ; final-expression ) {// body of the for loop} Initialize-variable: Initialize a variable in the first parameter. Condition-to-be-met: Define a condition on which the loop will iterate. Final-expression: Task to perform at the end of loop’s iteration Note: The parameters of the For loop are separated by a semi-colon “; ” and are all optional. Example: Let’s take an example where we need to print the first 10 digits starting from one. If we do it without a loop our code will look like: console.log(1); console.log(2); console.log(3); console.log(4); console.log(5); console.log(6); console.log(7); console.log(8); console.log(9); console.log(10); The output: Output is exactly what we wanted, but it’s not an efficient way of doing it. Let’s try using the For loop for solving the same problem. The code is as: for (let i = 0 ; i <=10 ; i ++){ console.log(i)} The output is exactly the same: If we go over the code, we created a block-scoped counter variable “i” and initialized it with an integer value 0. In the second parameter, we set a condition that we want to run until the counter variable reaches the value 10, and in the last parameter, we set a final expression to increase this counter variable by 1 every time the loop reaches the end of each iteration.

 How to work with Arrays using For Loop

Loops can also be used to iterate through arrays and their value, to demonstrate that, we will need an array. Create an array of numbers with the following statement: array = [1,5,88,24,25,137,37,28,173,222]; Let’s use loop access each element inside this array and print out its value by using the following statements: for ( i = 0 ; i < array.length ; i++){ console.log(array[i]);} The output is: Note: We used the condition, i < array.length because the index of the last element in the array, will always be one less than the length of the array and that is because in arrays the index starts from zero We can even use the For loop to traverse in the array from the last to first by using the code: for (let i = array.length-1 ; i >= 0 ; i--){ console.log(array[i]);} We initialized the counter variable with a value one less than the length of that array to access the last element of the array, and started reducing the counter variable by 1 in each iteration. The output is:

 The For-of loop

The For-of loop is used to iterate over iterable objects, these objects can be Arrays, Sets, Objects, and even Strings. The For..of loop returns the value of the elements of the iterable objects:

 Syntax of the for-of loop

for ( element of array ){// Body of the loop} element: is the name of the variable we are going to give to each item in the array. array: is the array that we are traversing through To better understand the working of For-of loop, let’s take an array of variables values: array = [1,4,56, "Cash", " Car", 63, 69, "Google", "Moon", "Mercury"]; Now, use the For-of loop to iterate through the elements using the following lines of code: for (elem of array ){ console.log(elem);} The output is: We have traversed through the elements of the array using the for..of loop.

 Looping through a string using the for-of loop

We can use the For-of loop to go through each character of a string value. For that let’s create a string variable using the following statement. var sentence = "Welcome to LinuxHint!"; Now, iterate through every character of this variable using the commands: for (char of sentence ){ console.log(char);} We get the following output in our console: As you can see, with the help of the For-of loop, we were able to access each individual character from within a string.

 The For-in loop:

The For-in loop is used to iterate over the properties of the elements inside the iterable objects, to understand this in a much better way we create an object containing key-value pairs using the following statements: const person = {firstName: "John", lastName: "Doe", age: 22, city: "Newyork"}; Let’s print the “key” values of this object by using the for..in.. loop through these statements: for (props in person) { console.log(props);} The output is: As you can see the for-in loop accesses the names of the properties of the items.

 Conclusion

The for loop is the most widely used loop; JavaScript comes with its variation of for loop, the for-in loop, and the for-of loop. We learned about the syntax and working of the for loops. After that, we learned about the for-in and the for-of loop and how they work and what they return along with their examples, and we even learned the difference between the two variants.

Events | Explained with Examples

JavaScript Events are actions that are performed on the HTML page or on the HTML elements either by the window object (DOM) or by the user. Events cause the execution of actions that result in the manipulation of the webpage or the execution of backend functionality. JavaScript is known to give a webpage the ability to “think and act” which is all possible due to Events. Events act as triggers that prompt the backend scripts to perform actions. They can be easily referred to as “things” that happen on a webpage, these events can be anything: loading a webpage, clicking an HTML button, or hovering the mouse over a specific HTML element. There are gazillions of events that can trigger JavaScript, we have events to trigger a function on mouse click, or on mouse hover, but we are going to cover working with events and JavaScript. A simple example of a JavaScript event being executed upon a button press is shown below:

 Event Handlers

Events are managed by event handlers; HTML provides the capability to add various types of event handlers on its elements, these event handlers allow the programmer to run JavaScript code by executing a function. There are 3 types of event handlers: Dom-on-event listener In-line-event listener addEventListener() method

 The DOM on-event listener

We can use event listeners on the DOM properties, such as triggering an event upon the complete loading of the webpage. These event listeners can also be added to HTML elements but with the restriction being one event listener per each HTML element. For example, we want to alert the user on the complete loading of the webpage, we can do that by accessing the window object of the DOM: <script> window.onload = () => { alert("The webpage has completely Loaded.");};</script> After running the HTML file you will see the following output: As you can see, after completely loading the webpage, the JavaScript alerts the user that the webpage has loaded. Note: the window object is used to work on global events.

 The inline-event Listener

One of the trivial methods when working with HTML and JavaScript is to use the inline event listeners, we do this by adding the event listener as an attribute of the element inside its tag. For example, in the above example, we added an “onclick()” event inside the button element, when we use the inline event listener we set it equal to a function that will get invoked when the event is triggered. <button onclick="btnClicked()">Click this Button</button> As you can see, btnClicked() is the function that will be executed on a button click. If we want to print the string to console “You have pressed the button” we can do that by writing the btnClicked() function like this: <script> function btnClicked() { console.log("You have pressed the button")}</script> When you run the HTML file you get the following output.

 Using addEventListener()

The third event handler is added using the addEventListener() method, This is the new and the most used way of handling events; to show this, we are going to create a div in HTML by using the following lines of code: <div id="demo" style="background-color: cadetblue"><p>addEventListener() Example</p></div> To add an event listener on this div you are going to use the following script snippet: <script> const div = document.getElementById("demo"); div.addEventListener("mouseenter", (event) => { console.log("The mouse has appeared"); }); div.addEventListener("mouseleave", (event) => { console.log("The mouse has left"); }); div.addEventListener("click", (event) => { console.log("Mouse Clicked on DIV"); });</script> If you look closely at the script snippet, you will notice that we are adding 3 different event listeners on this div, one when the cursor enters the div, second when the cursor leaves the div and last one when the cursor clicks on the div; After writing all this code, save it, reload the page, and you will get the following output: As you can see in the console, our event handlers are working and the JavaScript code is being executed. That is it for Events

 Conclusion

Events are the occurrence of such instances that prompt the JavaScript to perform some manipulation on the HTML elements or to perform back-end functionality. The event is used to give the HTML webpage the capability to think and perform actions, these events can be anything that a user does: clicking a button, pressing a specific key, or a specific mouse movement. There are some global events as well that can be accessed using the window object, such as the window.load(). We learned about various types of event handlers along with their examples.

Default Parameters | Explained with Examples

Parameters define the requirements for invoking a function. Oftentimes, we invoke a function, but we miss incorporating some arguments that are necessary for the output, and the JavaScript function either gives us an error or returns a NaN value. To avoid this undesirable outcome, we use default Parameters. Default parameters are the parameters that have defined their default values in case they are missing from the invoking function call. We are going to look over an example where we get a non-satisfactory outcome due to missing arguments and then we will fix it using traditional and default parameters. But first, let’s learn a little more about the default parameters.

 What are Default Parameters

In the ES6 version, JavaScript introduced a feature of setting up default parameters. When developing a full-stack application, we usually want to cover all of our ends that can return us any error. The issue of missing arguments in the invoking function call is one of such corners and the default parameter is the guard that we use to save us from unwanted outcomes. Declaring default parameters is rather easy. When defining the parameter of the function simply put the default value after the “=” sign. The syntax is as: function functionIdentifier (parameter = value) {// Body of the function} ; For example: functionprintName(firstName, lastName = `doe`) { console.log(firstName + ` ` + lastName);} printName(`John`); printName("John", "Who"); The output of both the commands is as: For the first function call, it used the default value “doe” for the parameter “lastName” and for the second it used both the arguments.

 How do Default Parameters work

Using the same function that we created in the above example, for the first case when both the arguments are present then the values inside the function call are used like so: And for the second case, in which one of the arguments was missing, the function used the value that we defined as the default value within the parameter like:

 Why use default Parameters

Typically when no argument is passed then the parameter is considered to be “undefined” by JavaScript. The traditional or trivial approach to avoid an unwanted output is to check the parameter for an undefined value. The trivial approach can be used with the following lines of code for a function to add 2 numbers: functionaddNumbers(num1, num2) {if (num1 === undefined) { num1 = 1; }if (num2 === undefined) { num2 = 1; }return num1 + num2;} console.log(addNumbers()); Even though we are not passing any arguments when calling the function inside the console.log() function, we won’t get any error. In fact, the output is as: As you can see we can handle the issue of missing arguments like this as well. However, being a good programmer is all about being efficient, and this trivial approach is not an efficient solution. If we were to solve the same problem using the default parameters, the solution would be much more concise like: function addNumbers(num1 = 1, num2 = 1) {return num1 + num2;} console.log(addNumbers()); As you can see, instead of writing numerous lines, we did it in a single line and the output is exactly the same with no errors and no NaN.

 Using default parameter value from an earlier parameter

In ES6, you can set a default parameter using the parameter before it. This is because the parameters are initialized from left to right. Resulting in the use of earlier defined parameters in the default value of later parameters. For example, take the following snippet: function getSome(a, b = a * 2) {return a * b;} console.log(getSome(2)); The function getSome() will take 2 parameters, if there is only one argument then it will assign the second parameter twice the value of the first argument. The output is as: Since, the parameters are initialized from left to right, if we use a later parameter as the default value of an earlier parameter then it will result in an error. Take the following code as an example: function errorGen(a = b, b = 2) {return a + b;} console.log(errorGen()); The above will meet an error since it’s trying to access the parameter “b” even before it is initialized. The output is as:

 Using functions as values in default parameters

In ES6, you can even use functions as the default parameter values. Try out the following lines of code: function calc(a, b = getValue(a)) {return a + b;} function getValue(num) {return num * 2;} console.log(calc(2)); As you can see, we are giving the function getValue(num) as a default parameter for b and we are passing the parameter a inside it. The getValue(num) multiples the argument passed to it by 2 and returns the value. That is why, when we pass 2 inside calc() function as a single parameter we get the following out: That’s it for default parameters.

 Conclusion

In ES6, a new feature was introduced which was the default parameters. To avoid meeting an error because of missing arguments JavaScript added this feature. Default parameters are used to put a default value of an argument at the time of writing that function. We learned about default parameters, how we can use default parameters to avoid unfavorable results, and why we should use default parameters as a replacement to the traditional/trivial approach along with its examples.

Comparison and Logical Operators | Explained

Comparison and logical operation are the core basics of computer-based machines. If you know a little about how computer-based machines work, then you will surely understand<< that their working is all based on two values which are called binary values, 0 and 1, or in simple words, true-false \ on-off. These values are deduced by using comparison and logical gates (actual physical devices on the chipset). The same concept is applied while developing a program to control the flow of the application. The comparison and logical operators that are available have the same meaning in every other programming language as well. Well, comparison and logical operators are mostly used with conditional statements like if, if-else. Let’s get started first with comparison operators.

 What are comparison operators?

Comparison operators, as the name indicates, are used to compare values of two or more operands. The resulting value is of the boolean type. These operators are listed as:
OperatorExplanationExample
==This is equal to thatX == Y
!=This is not equal to thatX != Y
>This is greater than thatX > Y
<is less thanX < Y
>=is greater-than OR equal to thatX >= Y
<=is less-than OR equal to thatX <= Y
===is equal to And equal type to thatX === Y
!==is not equal to OR equal type to thatX !== Y
Let’s Explain these operators with one example each. We’ll be using the browser’s console to show these examples. Is Equal to ‘ == ’ operator This operator compares the value on the left side with the right one and returns True if both the operands are the same, False if they are not equal. We declared two variables (x and y) with values 5 and 10 and tried to compare them with the statement, X == Y, and as a result, we got False. Here, is another example where we use the values 5 and 5 for the variable X and Y respectively, The output is True. Not equal to ‘ != ’ operator This operator returns True when two values are not equal to each other, False if they are equal. As you can see, it returned True because variables had different values Greater than “ > ” operator Comparing operands on both sides and returning True only if the Right-hand side value is bigger. Like this: We placed the values 5 and 3 in variables X and Y respectively, asked the program if X was greater than Y and it returned true. Less than “ < ” operator Comparing operands on both sides and returning True only if the left-hand side value is bigger. Since 23 is less than 41, it returns True. Greater than equal to “ >= ” operator It is the conjunction of both greater than operator as well as the equal to operator. Returns true if and only if the value of the variable on the left-hand side is bigger than or the same as the one on the right, else False First, we assign values 99 and 99 to variables X and Y respectively and try using the operator on these variables. It compares both the variables and returns True because they are equal to each other. Then we change the value of Y to 100 and try using this operator on the variables again. This time it returns False because 99 is neither greater than 100 nor is it equal to 100. Less than equal to “<= ” operator It is the conjunction of both greater than operator as well as the equal to operator. Returns true if and only if the value of the variable on the left-hand side is smaller than or the same as the one on the right. Otherwise, it will return False. In the above snippet, first, it returns true because the value 21 is less than the value 23. Afterward, we changed the value of the variable X to 23. The result is True because both the variables “X” and “Y” have the same values. Strict Equal to “ === ” operator Returns True if and only if, both the variables \ operands have the same value plus the same data type. Otherwise, it will return False. In the above code snippet, we created a variable with the name of “name” and gave a string value “LinuxHint”. When we try comparing this variable with a number it returns False because the operands are not of the same type. Then we compare this variable with the string “LinuxHint” and it returns true because the value of both the operands and the type is the same. To further clarify this value and type confusion, let’s look at this example. We created a variable “num” with string value “2”. We first try to compare it to a numerical value 2. It returns false because one is a string value “2” and the other operand is a numerical value 2. Later on, when we compare the variable num to string “2”. True – because the type and the value of both the operands involved were the same. Strict Not equal to “ !== ” operator If and only if the type and the values of both the variables involved are different, so the outcome will be True, otherwise False. Just like the last example, we created a variable “num” with a string value “2”, and tried to compare it with numerical value 2. The operator returned True because the types of both the operands were different. When we tried comparing it with the string value “2” it return False because both the operands were of the same value and of the same type.

 Logical Operators

Logical operators are used to implement logic gates and their truth tables in programming. These are used mostly while implementing a conditional block like if, if-else. These operators are listed as:
OperatorExplanationExample
&&Returns True, if All the conditions involved are true.X = 3 && y = 23
||Returns True, if any conditions involved is trueX =3 || Y = 23
!Negate, inverts the value !(X= 3)
Let’s Explain these operators with one example each.

 And Operator “&&”

The And operator returns True if and only if both the variables, or in some cases, both the conditions are returning True, else false. Since both the conditions were true, the AND operator returned True.

 OR operator “ || ”

The OR operator is used to implement the OR gate. Results are True if any of the involved conditions are True. As you can see, one of the conditions was returning true and the other one was returning false, but we still got the result as True, that is how we can conclude that this is used to implement the OR GATE.

 Negative Operator “ ! ”

A negative operator simply inverts the outcome of the condition. As you can clearly see, we created a variable “value” and set it equal to boolean true. And when we used the Negative operator on it, it inverted its boolean value.

 Conclusion

Comparison and logical operators are an essential part of programming as they allow the programmer to control the flow of the program by using certain conditions. So, we learned about the available comparison and logical operations along with their examples to get their clear understanding. Now, after practicing, you’ll be able to develop a Top-tier application in which you’ll be using these operators.

Classes | Explained for beginners

Classes in a programming language are a feature that belongs to the traditional object-oriented approach and, it has some of the same features. Class in programming is a structure to create objects Classes were added in 2015 with the release of the ES6 version of JavaScript. Classes are the mapping for real objects into programming languages objects.

 Why create a Class

Very precisely, to save time and to avoid redundancy, these are the main reasons why classes are used. For example, if you want to make objects of 50 people having almost the same properties: first name, last name, and age; You will have to write the structure of 50 different objects. But with the use classes, you can create a single template and map infinite objects on that same template. Moreover, referring to the object-oriented approach, classes are used to implement the concept of modularity within a project, and also to implement development processes like the incremental development process easily.

 How to define a class

To define a class, You use the reserved keyword “class” and then the name of the class and curly brackets after the identifier. The data of the class is written inside the curly brackets. A simple example of Person class would be like: class Person{// Data of the class - constructor, variables and methods}

 How to work with a JavaScript Class

To work with a class, it must have some properties of the object and a constructor method. To demonstrate the working of classes and objects we will be creating a class for people with the identifier “Person”. Therefore, to create a class of person you can use the following lines of code: class Person{// Later code will come inside here, inside the class} Class variables are variables that are known as the properties of the objects. These variables can also be variables required for a certain class method. For the Person class, to create the class variables: firstName, lastName, age, and job, the following code inside the curly brackets of the class will be used: firstName; lastName; age; job; The constructor method is automatically executed when a new object is created, the constructor method is used to initialize all the variables and the methods of the class. The constructor method is mandatory for a class to work, but it is optional for the developer to create a constructor method because JavaScript will create an empty constructor method for the classes without a constructor. The constructor method is created by using the reserved keyword constructor and by putting round parenthesis in front of it. Within these parentheses, you can define the arguments required for an object to be mapped on this class and even use default parameters. To create a constructor for the Person class the following code will be used to assign the values to the properties of the object. constructor(firstName="John",lastName="Doe",age=20,job="Freelancer"){this.firstName=firstName;this.lastName=lastName;this.age=age ;this.job=job;} As you can see in the above code, we are using default parameters to avoid an empty argument. Class methods are normal functions that are accessed by using the dot operator “.” with the identifier of the object, but unlike normal functions, the keyword “function” is not used to define a class method; rather You type the name of the method and put round brackets in front of it and write JavaScript code of the method enclosed in curly brackets {}. You are going to create a method that will print the details of the person object using the following lines of code: printDetails() { console.log("Name : " + this.firstName + " " + this.lastName); console.log("Age : " + this.age); console.log("Job: " + this.job);} You have a basic class of Person completed, the complete code of this class is as: classPerson { firstName; lastName; age; job; constructor( firstName = "John", lastName = "Doe", age = 20, job = "Freelancer" ) {this.firstName = firstName;this.lastName = lastName;this.age = age;this.job = job; } printDetails() { console.log("Name : " + this.firstName + " " + this.lastName); console.log("Age : " + this.age); console.log("Job: " + this.job); }}

 Mapping and using Objects against Classes

Now you have to map objects to this class. For that, you are going to create an object p1 and set it equal to the Person class’s constructor with the key “new”. You can even create more objects and give them whatever names you want. This would map our object variable to the class Person. We can create infinite amounts of objects against this class Person. p1 = new Person("William","Mark",35,"Writer"); p2 = new Person("Henry","Clark",22,"Auditor"); To access the printDetails() method of both the object we just have to use the dot-operator like: p1.printDetails(); p2.printDetails(); After executing the whole code, you will see this output on the console: As you can see in the snippet above, we printed out the details of 2 different objects having the same properties but different values.

 Conclusion

Classes are used to define a mapping for the objects having the same properties and functions. These classes are also called the implementation of modularity using the object-oriented approach. We learned what classes are, how to define them, how to work with them, and how to use them to create objects along with examples.

Regex | Explained with Examples

When a developer first lays his eyes on regular expressions or regex it seems gibberish. However they may look, regular expressions are extremely useful and make you an effective programmer. The Regex concept is a little complicated, however in this post, we will walk you through simple steps along with examples to help you master Regex.

 What is Regex?

Regex or Regular expression is simply a string that defines a pattern and is very useful in finding a pattern in a string or replacing a string with a matched pattern. To put it simply, suppose you want to validate an email address or phone number with a specified pattern, then Regex comes in handy. Regex Syntax: var myRegex = /abc/; We enclose a pattern in forward slash “/” as shown above. We can also use the RegExp constructor to define a Regex pattern: var myRegex = new RegExp('abc'); Now that we know what regex is and what is its syntax, let us now see how to specify a pattern using Regex.

 Specify Pattern using Regex

To specify patterns using regex we use metacharacters which are characters that hold special meaning. Metacharacters and what they represent in Regex is given in the table below:
Meta characterWhat does it do?
[] (Square brackets)Whatever we write in the square brackets will be matched with a given string. For example [abc] matches the a, b, and c characters with a specified string. We can also specify a range for example [a-f] is the same as [abcdef] or [1-5] is the same as [12345].
^ (Caret symbol)The Caret symbol is used to check whether a specified text or string starts with a certain character or not e.g. ^a matches with abc however ^a does not match with bac. The Caret symbol within square brackets is used to take the complement of specified characters. For example [^abc] specifies that except a,b, or c any character present will be matched.
$ (Dollar symbol)The $ symbol is used wherever we want to check whether a string ends with a certain character or not. For example, a$ means that whatever string we are matching with should have a at the end, that is amnesia will be matched with a$ however heart will not.
* (Star symbol)The star symbol matches 0 or more occurrences of the specified pattern or character present left from the star symbol in a string. For example, ma*n means that search m and a character in a string. Hence mn will have 1 match. Main will have no match as a is not followed by n and there is i in between.
+ (plus symbol)The plus symbol is just like a star symbol with the exception that it matches 1 or more occurrences of the specified pattern or character. For example, when mn string is searched for the expression ma+n there is no match however when the expression is searched for man there is one match.
{} (Braces)To have a clear understanding of braces let us first see the following code i-e {2,3} which means at least 2 and at most 3 repetitions is possible of the pattern left from it. For example, the expression a{2,3} when matched with the string “abc dat” will have no match however when the expression is matched with the “abc daat” it will have one match i-e daat.
| (Alteration)The Alteration or vertical bar symbol is used for the or operator. For example, the expression a|b indicates that a or b should be present in a specified string. Hence fgh has no matches and abc has 2 matches that are ab.
\ (Backslash)The purpose of backslash is to escape characters as well as escape all metacharacters. In simple words, if you are unsure whether a character contains some special meaning or not then place a backslash before the character. Hence that character will not be treated in any special way, for example, \$a expression will match any text or string that has a $ followed by a.
Now that we know how to specify patterns using Regex let us now go through some Regex methods to match a regex with a specified string.

 Test patterns for matching

Earlier, we discussed how we can use the RegExp constructor to initialize the RegExp object with a specified pattern. This RegExp object gives us many built-in methods and one of them is the test() method. The test() method is very useful as it checks a string for a specified pattern in the regular expression. The test() method returns a boolean value, that is if the specified pattern matches the string then true is returned, otherwise false is returned. To better understand the test() method let’s see an example: var myRegex = /Hello/; var output = myRegex.test('Hello World!'); console.log(output); // true In the above code first, we defined a pattern that is Hello and then used the built-in method test() on the specified pattern to check whether the string Hello World! contains Hello or not. The result is given below: Instead of the boolean value, the string match can also be returned with another built-in method which is the match() method. The code below is implementing the match() method: var myString = "Hello World!";// pattern var myRegex = /Hello/; console.log(myString.match(myRegex)); // Hello An array will be returned which will contain the input string to the match() method, the index on which the match is found as well as the match itself. If a match is not found then null will be returned: var myString = "Hello World!";// pattern var myRegex = /Hi/; console.log(myString.match(myRegex)); // null

 Pattern Flags

We saw that the RegExp object accepts a pattern; however it should also be noted that the RegExp can also take an optional flag parameter. Flags are just a little extra topping that changes the searching behavior. The first flag we will discuss is the ignore flag denoted by i. By default, pattern searching in Regex is case sensitive so to ignore cases we use the ignore flag (i) when searching for a pattern. For example: var myRegex = /hello/i; console.log(myRegex.test("Hello World!")); // true Although the pattern has hello and the string in the test method has the first letter capital, it’s still a match because we used the ignore flag (i) hence the result will be true: To use the ignore flag with RegExp object copy the following code: var myRegex = new RegExp('hello', 'i'); console.log(myRegex.test("Hello World!")); // true Similarly, we can use the global flag denoted by g whose function is to return all the matches in the string. Without the global flag, only the first match is returned. The below code uses the global flag: var myString = 'Hello World! and hello Universe!'; var myRegex = /hello/gi; var matches = []; var match;do { match = myRegex.exec(myString);if(match) { matches.push(match);}} while(match != null) console.log(matches); First, we initialized myString which contains the string that will be used for searching a pattern, and after that, we created a regular expression pattern that contains the global flag and ignore flag. The global flag will search for all the matches whereas the ignore flag will ignore case sensitivity. In the above code, another built-in method is used which is the exec() whose function is to return an array that contains the match. However, if there was no match between the pattern and the string then null will be returned. It should be noted that the exec() method only returns a single match at one time hence we use the do-while loop and push all the matches to the matches array. In the end, we console log the matches array which contains all the matches:

 Conclusion

Regex is a string that defines a pattern or finds a pattern in a specified string. We use the RegExp object or the forward-slash / to define Regex. The RegExp also takes an optional parameter i-e flag which changes the searching behavior. To specify patterns we use metacharacters which are some specific characters having special meanings. To test whether it matches with a string or not we use built-in methods like test(), match(), or exec(). In this post, first, we defined what is Regex and what is Regex syntax. Then we showed you how to specify patterns using Regex and test patterns. In the end, we discussed the two flags that are global and ignore flags.

How to destructure Objects and Arrays | Explained with Examples

The ES6 version came with a wave of new features, one of those features was the capability to destructure objects and arrays. Destructuring arrays or objects is the process of taking values from objects or arrays and assigning them to local variables using the destructuring syntax. Destructuring works by assigning the values of the elements of the array/object to multiple variables by using a single line of code, then you can access those values by using those new variables. Remember, there is no particular destructuring “symbol” or “operator”. Syntax The syntax of using the destructuring assignment is rather simple; to destructure the object into multiple variables: Use the curly Brackets { } after the variable definition Put in the variables inside the curly brackets then set it(whole variable declaration) equal to the object Objects: const {var1,var2} = objectName; Similarly, to destructure arrays to multiple variables, use the square brackets [ ] instead of curly brackets. Arrays: const [variable1,variable2] = arrayName; Note: In the case of destructuring objects, the name of the variables should be the same as the name of the properties of the object.

 Destructuring Arrays

Create an array containing random elements inside it to demonstrate the destructuring of arrays using the following command: user = ["Alberto", "Rodrigo", 25, "Male"]; You can see, we have an array with the details of a person. The traditional solution of storing the values of the elements of this array in local variables would be: const firstName = user[1];const lastName = user[2];const age = user[3];const gender = user[4]; This is a long process and requires more lines of code. Using the destructuring features the above code changes to: const [firstName, lastName, age, gender] = user; Just with that one line, we have created 4 variables and assigned them the respective values from the array. To verify this you can print the value of any of these variables with the following code: console.log(firstName); console.log(gender); The complete code snippet would be: array = ["Alberto", "Rodrigo", 25, "Male"];const [firstName, lastName, age, gender] = array; console.log(firstName); console.log(gender); You will get the following output: You can see, the variables had their values from the elements of the array.

 Destructuring Nested Arrays

Destructing even works with nested arrays. For example, take a nested array which can be created with the following lines of code: user = ["Alberto", "Rodrigo", 25, "Male", ["Mr.John", "Samantha"]]; You can see that the last element of the array is another array containing the names of the father and the mother of the person. We can destructure this nested array using the following code: const [firstName, lastName, age, gender, [fatherName, motherName]] = array; You can verify this destructuring using the following commands: console.log(firstName); console.log(gender); console.log(fatherName); console.log(motherName); The complete code snippet is: array = ["Alberto", "Rodrigo", 25, "Male", ["Mr.John", "Samantha"]];const [firstName, lastName, age, gender, [fatherName, motherName]] = array; console.log(firstName); console.log(gender); console.log(fatherName); console.log(motherName); You will see the following output on the screen when you execute the program. You can see that you were able to successfully destructure the array and verify the result in the end as well.

 Destructuring Objects

Suppose we have a “person” object: var person = { firstName: "John", age: 25, lastName: "Doe", job: "Auditor",}; And the key-value pairs are the properties of that person: first name, last name, age, and job. You can destructure this object using the following line: var { firstName, age, lastName, job } = person; Note: When you are destructuring an object, the name of the variables should match the name of the properties of the object otherwise, the destructuring will not work and the value of the variable would be undefined. You can verify the destructuring by printing the values of these variables onto the console by using the following lines of code. console.log(firstname); console.log(lastName); console.log(age); console.log(job); The complete code snippet is: var person = { firstName: "John", age: 25, lastName: "Doe", job: "Auditor",};var { firstName, age, lastName, job } = person; console.log(firstName); console.log(lastName); console.log(age); console.log(job); When you execute this program you will see the following output: You have successfully created an object, and that is it for destructuring objects and arrays.

 Conclusion

Arrays and objects can be destructured using the destructuring syntax, destructuring arrays and objects is a new feature that was introduced in the JavaScript ES6 release. Destructuring is the process of assigning the values of the elements/properties of arrays/objects to local variables by using a single line of code. In this guide, we learned how we can destructure arrays, nested arrays, and objects with the help of examples.

How to delay/wait code execution?

Functions that can delay or halt the execution of a chunk of code are very crucial in a programming language as they are a way of controlling the flow of the program. There are many built-in “delay” or “wait” functions available in most programming languages. But, there is no delay, wait, or sleep function because it is a scripting language and scripting languages are always synchronous and single-threaded. Initially, it may not seem a big deal, but as you progress in the world of programming you will realize the importance of “delay” and “wait” functions. So, if there is no wait \ delay \ sleep function then there is no way of controlling the execution of a program? Well, there are different functions and methods that help us achieve the same task.

 Using setTimeout() function

The first and the most common method in implementing a delay in the execution of a JavaScript code is to use the setTimeOut() method. You’ll do a very common mistake of assuming the syntax is: setTimeout( delay in ms ); Whereas in reality, this method takes a callback function. Keeping that in mind we can look at the syntax as:

 Syntax of setTimeout() function

setTimeout( function , delay in ms); To better understand the working of the setTimeout() method, let’s try and solve a problem. Example Suppose that we want to print numbers from 1 to 10, with a delay of 1 second in between each number. The traditional way would be: for (let i = 1; i <=10 ; i++ ){ setTimeout(1000); console.log( i );} The output of the code is instantly printing all 10 digits like: Because we are not passing anything to the setTimeout() method. To add the delay using the setTimeout() method we think that the correct way is : for (let i = 1 ; i console.log(i), 1000 );} Rather than getting a 1-second delay after every number, what we get is a 1-second delay in the start and then all the numbers are printed instantly. As shown below: We had the initial delay, but no delay after that. Why is that so? Well, the way the setTimeout() works is that it always runs in synchronous mode. This means that even having multiple calls to the same function will result in the delay of 1 sec. What we did was, we invoked each setTimeout() method one after another and due to the asynchronous nature of the setTimeout() method, it does not wait for the previous setTimeout() method to finish and then execute the next one. So ultimately we made 10 calls to setTimeout() method all having the same delay time. There is a way to fix this, and that is by using increasing delay timer like: setTimeout( () => console.log(i), 1000 ); setTimeout( () => console.log(i), 2000 ); setTimeout( () => console.log(i), 3000 ); The above code example of printing 10 numbers would become this: for (let i = 1 ; i console.log(i), i * 1000 );} We are using the increasing value of the “i” variable and multiplying it with the 1-second delay to create incrementing delays for each call of setTimeout()

 The output with this becomes:

We finally did it. But there is still something wrong here. That is the fact that calculating delays this way is very complicated especially when you are working in a real-world application. There is a way for that too, create your own delay/wait method.

 How to Code your own delay/wait function?

We want a better solution, what we can do is code our own “delay” method. We will be using the setTimeout() function and promise to help us create the “delay” method as: We will simply create a function with the name of “delay” and pass it time in milliseconds. This “delay” function returns a promise and won’t let the execution go on until the promise is resolved. function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms));} Now, we call this “delay” function with a “.then ” operator. Like this: console.log("Hello"); delay(2000).then(() => { console.log("World!"); }); The Output would be: We are creating a promise and setTimeout() method with some delay to resolve the promise. You can read more about JavaScript Promises. In case you want to get rid of the .then() method, and to chain the delays, what we can do is to use async and await with our “delay” function. async function demo() { console.log("This is a"); await delay(1000); console.log("LinuxHint"); await delay(1000); console.log("Tutorial!");} Note: we need to add the async keyword with the function that calls the delay() method. If we run the program what we get is this: Coming to our problem, the number printer from 1 to 10, we need to create it inside an async function and call the “delay” method which we just created like: async function numberPrinter() { for (let i = 1; i <= 10; i++){ console.log(i); await delay(1000) }} And we need to call this function with: numberPrinter(); The output that we get with this is: That is it for our “delay” function.

 Conclusion

There is no built-in wait, delay, or sleep function, but we can use the setTimeout() method to mimic the delay behavior and we can even code our own delay() method to create a delay in the execution of the program. We have learned how setTimeout() method works, how it is common to misunderstand its working and usage. Moreover, we learned how to combine the setTimeout() method with promises to create our own delay method, and we also learned how to use async and await on our function to wait and then continue the execution.

How To Define Functions | explained for beginners

Becoming a good programmer means writing such code that is reusable. A good practice is to write code in small chunks that help to perform a task, this code is not executed until it is required. This is where functions enter the picture. Functions allow dividing code that performs the same task and puts them in a small block. This block is executed whenever it is needed, which means it helps us in achieving modularity of code.

 What are functions?

As explained above, Functions are a set of statements that help the programmer to perform a specific job. The function is not executed until it has been invoked by some event. For example, a button that the user presses, or a timer that reaches a specific number and invokes the function. Bottom of the story, functions need to be invoked to execute them. We have explained what a function in general is, but how do you define a function?

 How to define a function?

In JavaScrip by using the keyword “function”, we can define functions. After that use the following syntax: function FunctionName ( params) { // Javascript Code herereturn (Return-Value-Here)} The key points for defining a function are: Using the reserved keyword “function” Giving a name to the function Putting round brackets after the function name Providing a list of required parameters to invoke the function within the round brackets JavaScript code that the function will execute enclosed within the curly brackets {} A return statement within the curly brackets For example, a simple function that says “Hello world” would be like: function helloWorld (){ console.log("Hello world, This is a LinuxHint tutorial");} Note: As you can see, the return statement is missing, that is because some functions don’t require returning a value, such functions are called Void Functions. Now that we have created a function but we are not getting any output because we have not invoked/called the function.

 How to call/invoke a function?

Write the name of the function and put round brackets in front of it to invoke it. However, if the function requires some parameters, then you need to pass on those arguments inside the round brackets. As far as the function that we created above is concerned, let’s try invoking it. As we have already discussed how to invoke a function, we use the command: helloWorld(); We will get the output as: We have tested creating a function and we have successfully invoked that function as well.

 How to define a function requiring arguments?

Now, let’s create a function that requires some arguments to be passed inside it to execute. In the following example, we are creating a function that takes a number as its params and prints the number’s table till 10. The code snippet of the function is as: function tablePrinter(number){ i=1; while(i<=10){ console.log(number +" x" + i + " = " + number * i); i++; }} Note: We are using a While-loop inside the function, if you are new to programming then you can read about the While-loop. Now that our function is done, it’s time to execute it by passing it a number as an argument like: tablePrinter(5); We get the following results. And that’s about it for this post.

 Conclusion

Functions are a crucial part of a programming language. JavaScript has its method of defining and invoking a function and that is exactly what we have learned, how to write/define a function. We learned about how to use arguments and parameters in functions as well and how they actually help in programming. Now with this understanding, you can move forward with your learning progress.

How to append a child in DOM using the appendChild() method?

If you want to change any element in HTML using scripting language then you have to refer to DOM also known as Document Object Model. DOM at its very core is a simple programming interface for that HTML file or in other words for the specific webpage. No scripting language is of any use without a DOM interface when it comes to manipulating HTML elements. One of the most common web page manipulations is to replace a node or to add a child node inside a parent node. This can be done through the appendChild() method.

 What is .appendChild() method

The .appendChild() method is an in-built JavaScript function that is used to add a child node under a parent node. The .appendChild() performs this feat by making use of the DOM Node Interface. We are now familiar with what it does, so let’s look over its syntax.

 Syntax of .appendChild() method

The syntax of .appendChild() is pretty self-explanatory. It is as: parentNode.appendChild( childNode ); As you can clearly see, It consists of the following: parentNode: The element in which the other node is to be appended. childNode: The element to be appended.

 When is appendChild() method used

The .appendChild() appends a newly created element inside the DOM. It is also used when you have to rearrange an already existing element. In most cases, both of the features, rearranging the existing elements, and creating a new element, and then adding it to the DOM is done upon an event invoked due to the user’s interaction with the webpage. This event could be clicking a button on the screen, a specific mouse location, or even a specific key-stroke.

 Example

We can’t learn anything until we try it out. So let’s try using the .appendChild() method. We shall: Create an HTML Page with a parent node Create a button that will invoke the appending process Create a child node. Append the child node in the parent node on the button press. Let’s start with the first step which is to set up an HTML page. Create a parent node by creating a div with an id =“demo”: Inside this div, we give it a child node which is a <p> tag: <center> <div id="demo"> <p>This is paragraph 1 inside "div" tag</p> </div></center> Let’s make the parent Node which is in our case the tag a bit prominent as well by giving it a background color. To do that, use the id=” demo” and give it some CSS styling with the following lines <style> #demo { background-color: cadetblue; }</style> We will get the following results. Now we know that the parent Node <div> of <p> tag is highlighted. If we add any child node inside this parent node, the highlighted area would increase. Coming back to appending a child node. Let’s create a trigger to append a child node, and for that purpose, we are going to add a button on-screen with the following line: <button onclick="btnClicked()">Click to appendChild</button> With this, our output becomes: We need to declare the function that will append a child node inside the div on every button press. Create the function like this: let counter = 2;function btnClicked(){// Add the later code inside here.} As you may notice, we created a variable called “counter”. This variable will keep a check on how many child nodes we have appended in the parent node. Since we already have a <p> tag as the first child, we start the counter from “2”. Now we need a child node. For this, we are going to create a <p> tag with some text inside it. For creating a <p> tag, we first need to create a TextNode and a paragraph node and then append the text node into the <p> tag node. Create a TextNode with the following command: textNode = document.createTextNode("This is paragraph "+ counter + ‘ inside "div" tag’); As you can see we are using the counter value to prompt the user on how many child nodes are present in the parent node. Next up is to create the <p> tag element: pTag = document.createElement("p"); Now, we need to add the TextNode into the pTag: pTag.appendChild(textNode); Lastly, we need to append this pTag inside the div with the id=” demo”: parentNode = document.getElementById("demo"); parentNode.appendChild(pTag); Before exiting the btnClicked() function, we need to increase the value of the counter as well: counter++; The complete code snippet will look like this: <script> let counter = 2; function btnClicked() { textNode = document.createTextNode( "This is paragraph " + counter + ' inside "div" tag' ); pTag = document.createElement("p"); pTag.appendChild(textNode); parentNode = document.getElementById("demo"); parentNode.appendChild(pTag); counter++; }</script> Time to finally run our webpage and look at the results. You should see this on your screen: There you have it, we have successfully appended various child nodes inside a parent node. We can also confirm it by examining the parent node inside the browser’s developer tools. We can clearly see that all the child nodes (<p> tags ) are indeed appended into the div with the id=” demo”.

 Conclusion

The .appendChild() method of JavaScript is used to append a child node inside a parent node with the help of the DOM node interface. Manipulating the elements of the webpage using a scripting language is an important task. One of the common tasks while manipulating web pages is to append elements as child nodes to other elements. We learned how the .appendchild() method works, its syntax, and when it is used. We created an HTML webpage, a parent node, and appended child nodes inside it using the .appendChild() function.

JavaScript Testing | An Introduction

Testing is by far the most important thing in the software development life cycle because without testing the product has no integrity. No renowned company will release a product to the market without testing it out first because testing ensures quality. In JavaScript, there are various tools and libraries that are used for testing. Some of the famous tools for testing are Jest, Mocha, and Cypress. In this post, we are going to go over the following topics: Why is testing important? Different Types of testing What are the different concepts of testing? Brief Introduction and installation of Jest, Mocha, and Cypress.

Testing | Why is it important?

As already mentioned above, no company wants to release a product full of bugs and ill-optimization protocols, because this would not only ruin the reputation of a company but also ruin the user’s experience. Testing is as important as coding the programming itself, from a programming perspective we can define the importance of testing with 3 simple concepts: The integrity of the code Optimization of the code Fixing regression bugs The integrity of the code is to know that the code of a specific product is producing the correct and desired results. For this purpose, manual testing is perfectly fine but automated testing is the go-to option as automated testing provides a feature of running tests automatically every time you make amendments to your code. Optimization of the code: There are various solutions of reaching the desired output but not all of them are optimal. Testing helps us discover the absolute best solution to reach a certain outcome. In programmatical terms, testing helps us reduce the load on both the server and on the client-side application while returning accurate results. Fixing regression bugs: Regression bugs occur when a newer feature contradicts with an older feature, or when adding a new method to the code causes the other functionalities to malfunction. Automated testing helps us discover and fix such regression bugs.

 Types of testing:

The most widely used types of testing are: Unit Testing Integration Testing End-to-End Testing Unit Testing: Unit tests are very small and concise tests that are mainly focused on executing the functionality of a small-scale module of a program. For example, a program has a feature to calculate the square root of numbers, testing this small feature would be called unit testing. Integration Testing: Sometimes modules of a program are dependent on other modules of the same program, integration testing verifies that such integrated modules are working correctly with each other and producing the desired results. End-to-End Testing: This testing is used to verify complex functionalities of the program, for example, imagine you have a process of registering your profile on your website, then the steps of creating your account, verifying your email address, adding personal information, and uploading your profile picture will all be included in a single end-to-end test. These types of tests often require some external dependencies to work, this is also known as functional testing. The first block of testing is the unit testing, then we move on to the integration testing and the last block is the functional testing.

 Software Testing Concepts

Now that you are familiar with the reason for the need for testing in the software development life cycle and the different types of testing, the next thing you need to learn is the various types of software testing concepts. There is a very huge number of software testing concepts and we are not going to over all of them, rather we are going to cover a few crucial concepts which are: Mocking Matchers Mocking: Sometimes, an object or a feature of the program is dependent on other objects or services, that is why while testing the object we isolate its behavior by replacing all the other dependencies with “mocks” to mimic the behavior of real-world objects. For example, we mimic the behavior of a database and test out the interaction between our object and the “mock database”” that we just created. Mocking helps increase the speed of testing by removing the chances of unreliability of external dependencies. Matchers: Matchers is a very basic concept, it is a function that allows you to verify the output of a method/feature in various different ways against our desired output. Matchers are mostly used for unit testing purposes.

 JavaScript Testing Tools

Now you are familiar with all the prerequisites of testing and next up the list are the most widely used tools for testing, which are as: Jest Mocha Cypress

 Jest

Jest is probably the most famous and the most widely used testing tool available, Jest is a testing framework developed by Meta (previously known as Facebook). The most prominent thing about jest is that you don’t have to configure it after installing it, it is a ready to use testing framework. One of the key features that Jest provides is its ability to run tests in parallel, as a result, greatly increasing speed while testing. To install Jest: Type in the following command in the terminal: npm install --save-dev jest

 Mocha

Mocha is also a flexible javascript framework developed with the sole purpose of testing. The aim of mocha framework is to make testing really easy and time-saving. Unlike Jest, mocha requires some configuration after installing it. To install Mocha: Type in the following command in the terminal: npm install --save-dev mocha

 Cypress

Cypress is probably the latest of the bunch, it focuses mainly on end-to-end and provides ease of use to complete testing beginners. Cypress uses JavaScript stacks to manage complex functional testings. The cyprus tests are executed in the browser itself, which results in close to zero lag. To install Cypress: Type in the following command in the terminal: npm install cypress --save-dev That is all for a basic introduction of testing and Javascript tools that are used for testing.

 Conclusion

Testing is the most crucial step in the software development life cycle. To understand testing, you must understand the importance of testing. In order to get started with testing and to maintain the integrity of your program, you should be familiar with various software testing concepts. We briefly went over the main software testing concepts in this post. Afterwards, we learned about the different tools that are used for testing and how to install them.

JavaScript startsWith() method | Explained with Examples

The String data type (high-level programming language) allows us to store strings. Like any other high-level programming language, string data type offers us some built-in methods which are predefined code that we can access by calling that method name. One such built-in method is the startsWith() method. In this post, we will discuss what the startsWith() method is and then we will implement some examples on the startsWith() method.

 What is the startsWith() method?

The startsWith() method checks the starting of a string for a specific character or a specific substring and is a built-in method of the String class. It returns true if the string is present at the start, otherwise, it returns false. It should be noted that the startsWith() method does not change the original string The syntax of startsWith() is given below: myString.startsWith(stringToBeSearched ,atPosition); startsWith() method takes two parameters: stringToBeSearched which is the substring or characters that we provide. The startsWith() method searches for these characters in the original string. This argument is mandatory. atPosition which is an optional parameter that we provide the startsWith() method so that the startsWith() method can start its searching from that position or index. From the syntax, we can also observe that the startsWith() method is invoked with a string class.

 Example 1:

In this example we will simply initialize a string and then implement the startsWith() method on that string by giving a substring as a parameter to the startsWith() method: var myString = "Hello! My name is Josh"; console.log(myString.startsWith("Hello")); // true The startsWith() method will check whether myString starts with Hello or not. Let’s see whether the startsWith() is case sensitive or case insensitive: var myString = "Hello! My name is Josh"; console.log(myString.startsWith("HELLO")); // false As the result is false, hence we can conclude that the startsWith() method is case sensitive.

 Example 2:

Now that we have implemented a simple startsWith() method example, let us implement another example by defining the position at which the startsWith() method should start searching for the string: var myString = "Hello! My name is Josh"; console.log(myString.startsWith("name",10)); // true We have provided the substring “name” and the position is 10. The “name” is present on the index 10 hence it should return true: If we change the index then it should return false: var myString = "Hello! My name is Josh"; console.log(myString.startsWith("name",5)); // false

 Conclusion

The startsWith() method is an inbuilt method of string class that searches a substring in the original string and returns a true value if the substring is present at the start of the original string otherwise it returns false. The startsWith() method is case sensitive, does not change the original string and the first character of the string at index 0 and second at index 1, and so on. In this post, we discussed what the startsWith() method is along with implementing three examples.

Popup boxes

JavaScript is a high-level web programming language that gives our web pages and web applications interactivity. JavaScript offers built-in global functions that are used to display messages for a variety of purposes. The various popup boxes that are available can be used to notify, warn users as well as to display a simple message or take the user’s confirmation or user’s input. Popup boxes aren’t utilized excessively as they halt other parts of the program until the pop-up is closed. There are three different popup boxes available; alert, Prompt, and Confirm Box and we will explore each of the popup boxes in this post.

 What is the alert box?

The alert box is a box shown at the top center of the browser window and it is mainly used to show warnings to the user. Other parts of the program would stop executing unless the user closes the alert box. To close the alert popup box, simply click on the ok button present in the alert box. The syntax for the alert box is: alert("Warning"); Let us see an example where we are displaying a Hello! Message in the alert box. The JavaScript code is present below: <!DOCTYPE html><html lang="en"><head><title>Alert Example</title></head><body><!-- Button to execute myFunc --><button onclick="myFunc()">Click Me</button><script>// function to show alert box function myFunc(){ alert("Hello!");}</script></body></html> In the above code, we defined a button and initialized an onclick event on it which means whenever the user clicks on the Click Me button, myFunc() will execute. After the initialization of the button tag, we initialized the script tag in which all of our JavaScript code will be present. Inside the script tags, we defined a function and inside the function, we showed an alert giving it the message of Hello! The output of the above code is shown below: We can see that when the user clicks on the button, the Hello! alert showed up.

 What is the Prompt Box?

The prompt box is mainly used to get input from a user and appears at the top center of the browser when invoked. The input data is also available after we close the prompt box and if you leave the input field in the prompt box empty then it will return a null value. The syntax for the prompt box is: prompt("Prompt Message Here"); Let us go through an example to better understand the prompt box. <!DOCTYPE html><html lang="en"><head><title>Prompt Example</title></head><body><!-- Button to execute myFunc --><button onclick="myFunc()">Click Me</button><script>// function to show alert box function myFunc(){ var name=prompt("Enter your name"); console.log(name);}</script></body></html> In the above code, We are taking an input using the prompt box and saving it to the variable name. After the name is saved, we console log the user name that was entered. The output of the above code is below: We will see the name on the console window now:

 What is a Confirm Box?

The third and final type of popup box JavaScript offers us is the confirm box whose function is to get permission or authorization from the user. If the user gives permission then he/she has to click on the ok button otherwise he/she has to click on the cancel button. The syntax for confirm box is: confirm("Permission goes here"); Now let us go through an example of the confirm box. <!DOCTYPE html><html lang="en"><head><title>Confirm Box Example</title></head><body><!-- Button to execute myFunc --><button onclick="myFunc()">Click Me</button><script>// function to show alert box function myFunc(){ var myValue;// check whether user clicks on the ok button or cancelif (confirm("To proceed press a button!") == true) { myValue = "OK pressed!";} else { myValue = "Cancel!";} console.log(myValue);}</script></body></html> In the above code, Inside the function, we are checking whether the user clicked on the “ok” button or the cancel button. If the user clicks on the OK button then we will see “Ok Pressed!” In the console log otherwise, we will see “Cancel!” In the console log. Let’s see the output in the console log when we click on the ok button of the confirm box: Now let’s see the output when we click on the cancel button in the console log: The console shows the following output:

 Conclusion

JavaScript offers us three kinds of pop-up boxes which are used to show a message, warning, or notification to a user using our web application or webpage. The three popup boxes are; alert, prompt, and confirm box. The alert popup box is used to show a warning to a user whereas the prompt popup box is used to take input from the user and the final confirm box is used to take permission from a user. In this post, we discussed the three popup boxes along with their implementation and screenshots of the output.

Promises | Explained

JavaScript is a high-level programming language where code is executed line by line which means that the next line of code is only executed once the previous line of code is completely executed. To solve this problem, JavaScript offers callback functions that are asynchronous equivalent to a function. Asynchronous code is executed immediately and unlike synchronous code, it does not wait for the previous line of code to finish executing. However, when we are dealing with multiple asynchronous operations, using callbacks is not a good choice as the code becomes confusing, unmanageable, and difficult to understand or debug. Hence the solution is to use Promises. In this post, we will go through the concept of Promises along with examples.

 What are Promises?

A promise is an operation or task that will be completed in the future. Promise syntax is given below: Promise Syntax: let myPromise = new Promise(function(resolve, reject){// code}); As we can see from the above-given syntax of Promise, the promise constructor takes only the callback function as an argument. In the callback function, we have the resolve and reject arguments where resolve is called when the operations performed inside the callback function are successful. However, if the operation is unsuccessful then call reject. To put it simply let us suppose that your birthday is coming up and your mother promises you to get you a new laptop. You haven’t received the laptop and you cannot be really sure whether you’ll get the laptop or not until your birthday. Your mother might buy you a laptop or she can change her mind and buy you something else. This is a promise in layman language. Every promise has three states or possibilities: Pending: You are not sure whether you will get the laptop or not; undefined. Fulfilled: Your mother buys you the laptop; result value. Rejected: Your mother doesn’t buy you a laptop; error object.

 Advantages of Promises

Asynchronous operations are handled in a simpler way Code readability is improved hence debugging becomes easy Error handling is easier than events or callbacks. The flow of control is better defined by asynchronous code. Before going to the Promise examples, let us go through another concept within promises that are promise consumers whose function is to consume Promises by registering functions using: .then(): When a promise is resolved or rejected, this method is called. .catch(): When a promise is rejected or an error occurs during the promise’s execution, this method is called.

 Example:

In this example, we will check whether two numbers are equal or not using promises, and based on whether this operation is successful or not, we will display output. // Promise initializing// Promise initializing varmyPromise = newPromise(function(resolve, reject) {const num1 = 4;const num2 = 4;// compare two numbersif(num1 === num2) {// when operation is successful resolve(); } else {// when error comes reject(); }});// Promise Consumers myPromise. then(function () { console.log("Operation Successful"); }). catch(function () { console.log('Error Occurred'); }); We initialized the Promise with the name myPromise and provided a callback function. In the function, we created the two numbers that we want to compare We used the if-else statement to see if the numbers are equal or not And then we included the promise consumers If promise operation is successful then .then consumer will be invoked and the console will display Operation Successful If a promise is not successful then you will see a message that says “error occurred” on the console Since the operation was successful, we see Operation Successful in the console log. Let us now change the numbers initialized in the call-back function to see whether the catch function detects an error or not. // Promise initializing varmyPromise = newPromise(function(resolve, reject) {const num1 = 5;const num2 = 4;// compare two numbersif(num1 === num2) {// when operation is successful resolve(); } else {// when error comes reject(); }});// Promise Consumers myPromise. then(function () { console.log("Operation Successful"); }). catch(function () { console.log('Error Occurred'); }); Since the numbers are not equal now, the reject() function will be invoked and the error will be cached by the catch function:

 Conclusion

A promise is an operation that is completed in the future and helps developers to implement asynchronous code. Promises are preferred over callback functions as promises are much more cleaner hence improving readability, and debugging of the code, it has better error handling as well as multiple asynchronous operations are better handled with promises. A promise can be fulfilled, rejected or it is pending. In this post, we went through Promises and explained Promises with the help of an example.

Template Literals | Explained

JavaScript is a high-level web programming language that provides us with string data type where we can store strings. Strings can be implemented with single quotes or double quotes (‘’ or “”). var myString = "Hello World!"; However, the string data type is limited and does not offer many functionalities like a high-level programming language(python, ruby) gives its developers. This problem was solved when JavaScript introduced Template Literals in ES6. Let us see what template literals are in this post.

 Template Literals

Template Literals gives us the ability to work with strings with more control and more power over the traditional string data type. Unlike strings, Template Literals use backticks “ rather than single or double quotation marks as shown below: var myString = `Hello World!`; Some of the features Template String provide us are: Interpolation: assigning variables and expressions inside a Template Literal. Multiline strings: We don’t need /n to go to another line, we just simply go to another line in Template Literal and the browser knows that it has to show that string on another line. Tagged Templates: It changes the template literal, and then after changing the template literal returns the resultant string. Tagged templates are just like functions with the exception that they are called without the () parenthesis. Let’s explore these features one by one:

 Interpolation

Variables and expressions can be easily interpolated into strings using template literals. Embedding an expression inside the template literal is known as Interpolation. We can achieve interpolation by using the ${someVar} syntax. Let’s see an example: var myString = `Hello World!`; console.log(`He said: ${myString}`); In the above code, we are initializing a variable and accessing it inside a string using the interpolation syntax. And to display the result onto the console, we are using the console.log() method:

 Multiline Strings

Another application of the Template Literal is that it gives us the ability to easily manage or write strings in multiple lines. Before Template Literals, it was a bit difficult and tricky as we had to use the backslash inside double quotes to tell the browser that the string should be on the next line. For example: var myString = "Hello\n"+"World!"; console.log(myString); In the above code, we initialized a string and used \n to tell the browser that the string after \n should be on the next line. Now let’s see how we can achieve the same functionality using Template Literal where we will simply write the second string on another line: var myString = `Hello World!`; console.log(myString); We can see that Template Literals made it very easy for us to write multiline strings and it is more easily readable and understandable.

 Tagged Templates

Another powerful feature Template Literals gives us is the Tagged Templates which simply modify a Template String by appending a function name to the beginning of the template string. In simpler words, a tagged template changes the template literal and returns the resultant string. Tagged templates are defined exactly like a function however when you call a template tag you don’t use the () parenthesis. The syntax for initializing a tag function is given below: function tagName(literals, ...substitutions) {// return some string} The tag function takes two arguments; the first is the literals which indicate the literal strings and the second is the …substitutions in which the subsequent inputs parsed for each substitution are stored. Now let us look at an example to implement a tag function: // Tag Template function myTagName(myString) {return myString;}// creating tagged templateconst output = myTagName`Hello Name`;// display result console.log(output); In the above code, we have created a function that is returning a string. After that, we created a tagged template and then called the above tag template function for which the syntax used is: myTagName`Hello Name` where the myTagName is the template tag and the Hello Name is the template literal. In the end, we displayed the result using the console.log() method: Let us now look at another example where we will pass literals as well as substitutions to the tag function: // values let greet = "Hello!"; let name = "Jhon";// tag function function transform(literals, ...substitutions) { console.log(literals); // ["", " my name is "] console.log(substitutions); // ["Hello", "Jhon"]}// call Tag Literal function transform`${greet} my name is ${name}`; In the above code, we first define the transform tag function which takes in two arguments; “literals” that is an array and has static content (“my name is”) while the substitutions rest parameter is also an array having all the tags(greet, name). The output of the above code is shown below:

 Conclusion

The standard datatype String provided by JavaScript was not powerful enough hence JavaScript introduced Template Literals in ES6. Template Literals give us more power over strings and are initialized using backticks . In this post, we saw what Template Literals are along with the features Template Literals offer us over the standard JavaScript string.

What Is AJAX?

Asynchronous execution code is opposite to synchronous in which your code does not have to wait for a statement to finish executing but can continue executing in parallel. Asynchronous execution is achieved with the help of AJAX. In this post, we will discuss what AJAX is, the stepwise working of AJAX, and walk through an example to better understand the implementation of AJAX.

 What Is AJAX?

AJAX, which stands for Asynchronous Javascript and XML, is a method(not a programming language) that is used for web applications to transmit and receive data from the server asynchronously, without affecting the rest of the page’s content or requiring a page reload. The abbreviation XML stands for Extensible Markup Language that is used to encrypt messages so that it can be read by humans and machines. XML is similar to HTML, but it lets you build and customize your own tags. AJAX communicates with the server using the XMLHttpRequest object, JavaScript/DOM to make requests, and XML as a data transmission mechanism. It became popular only when google put it in google suggest in 2005 To put it in simple words AJAX is a method of reducing the server-client interactions which are accomplished by only updating a portion of a web page instead of updating the entire webpage. The goal of AJAX is to send small quantities of data to the server without having to refresh the page.

 StepWise Working of AJAX

Some event is executed and the browser creates an XMLHttpRequest object after which the HttpRequest is sent to the server. The server gets the HttpRequest and then processes it, after processing, the server generates a response and sends the response back to the browser with some data. The returned data is then processed by the browser with the help of JavaScript and depending on the response JavaScript updates the contents of the webpage. Let us go through some examples to better understand AJAX.

 Example 1:

This example will demonstrate how to change the content of an h2 tag using AJAX. First, we will implement the structure of our web page using HTML. <div id="example"><h2>The XMLHttpRequest Object</h2><button type="button" onclick="loadDoc()">Change Content</button></div> In the above code, we defined a div container and gave it the id attribute due to which we can reference this div container later in our JavaScript code. This div section is defined so that it can display information from a server. Next, we defined an h2 tag and a button in which we passed an onclick event. Whenever a user will click on this button, an event will be generated and the function changeContent() will be executed. functionchangeContent() {// XMLHttpREquest Object initialization constxhttp = newXMLHttpRequest();// using onload built-in function xhttp.onload = function() {// updating div element content document.getElementById("example").innerHTML =this.responseText; }// get file ajax_info.txt xhttp.open("GET", "ajax_info.txt"); // Send Request xhttp.send(); } Now that we are done with the HTML page setup, we need to write some script code. For this tutorial, we are going to be including JavaScript code inside the <script> tag. In our script code, we first need to create the function changeContent() that will be executed with the click of the button, we can do that with the following lines of code: functionchangeContent() {// XMLHttpREquest Object initialization constxhttp = newXMLHttpRequest();// using onload built-in function xhttp.onload = function() {// updating div element content document.getElementById("example").innerHTML =this.responseText; }// get file ajax_info.txt xhttp.open("GET", "ajax_info.txt");// Send Request xhttp.send(); } As you can see in the above code snippet, the function generates a new XMLHttpRequest and waits for the response from the server. Upon receiving the response, the content of the div will be replaced by this function. Let us now create a file with the name of ajax_info.txt and write some dummy information in this file for example: The whole code is given below: <!DOCTYPE html><html lang="en"><head><title>AJAX Example</title></head><body><div id="example"><h2>The XMLHttpRequest Object</h2><button type="button" onclick="changeContent()">Change Content</button></div><script> function changeContent() {// XMLHttpREquest Object initializationconst xhttp = new XMLHttpRequest();// using onload function xhttp.onload = function() {// updating div element content document.getElementById("example").innerHTML =this.responseText;}// get file ajax_info.txt xhttp.open("GET", "ajax_info.txt"); xhttp.send();}</script></body></html> The output of the above code is provided below: We can see that when the user clicks on the button, the text “changes” to the text that was present inside the ajax_info.txt file.

 Conclusion

JavaScript executes code line by line that is called synchronous execution and hence AJAX comes into play as it is a method that helps in implementing asynchronous execution of the code. In asynchronous execution a statement or a line of code does not have to wait for the finishing of the previous line of code and both can execute parallel. AJAX is used to transmit and receive data from the server asynchronously without affecting the rest of the page and doesn’t even require the entire page reloading. In this post, we saw what AJAX is and then we went to see how AJAX works by describing the process stepwise, and at the end, we provided you with an example to make your concept clearer.

How To Use Object Methods?

JavaScript is an open-source, high-level, object-oriented (oop), web programming language that makes our web pages and web applications interactive and dynamic. As JavaScript is an OOP language hence everything is an object and an object is anything that has some properties and attributes The object is a non-primitive data type that stores collections of elements in key-value pairs. To work with objects, we can call methods on those objects as well as JavaScript offers us some built-in methods (predefined block of code) that we can use to work with objects.

 What are Object Methods?

Object methods of JavaScript are some specific functions or actions that can be performed on the specified object. To access an object method, the syntax is given below: The method is invoked by calling the method name after the object by using the dot operator. myObj.methodName(); myObj is the object on which a method is called. Let us go through an example where we will initialize an object and then call a method on that object: // Create Object Student var student = { firstName: "Peter", lastName: "Parker", fullName :function() { returnthis.firstName + " " + this.lastName; }};// call Object Method fullName console.log(student.fullName()); The output of the above code is given below: Now that we see how to call an object method, let us discuss some of the built-in methods of the global Object that we can call and use.

 Object.create() method

The Object.create() built-in method is used to create a new object and then link the newly created object with a specified object. The advantage of the Object.create() method is that we can create a new object by using the specified object prototype. Let’s demonstrate the phenomenon with the help of an example of the Object.create() method: // Create Object Student var student = { firstName: "Peter", lastName: "Parker", fullName :function() { returnthis.firstName + " " + this.lastName; }};// create new object varnewStudent = Object.create(student);// change last name of student newStudent.lastName = "Alberto";// call Object Method fullName console.log(newStudent.fullName()); // Peter Alberto In the above code, we initialized an object “student” and after that, we created a new object “newStudent” using the Object.create() method, this new object is mapped on the student object’s prototype. After that, we changed the last name of the new object and then called the fullName() method on this new object. The output is given below: As we can observe that apart from the changed last name, the newStudent object has the same properties and method as the student object.

 The Object.keys() method

As objects store key-value pairs hence to get those keys we use the Object.keys() method. The Object.keys() method returns an array of keys. Let us initialize an object and call the Object.keys() method on that specific object: // Create Object Student var student = { firstName: "Peter", lastName: "Parker"};// get keys of the object Student console.log(Object.keys(student)); // [firstName,lastName] We will see in the output an array that will have the keys of our object student: // Create Object Student var student = { firstName: "Peter", lastName: "Parker"};// get keys of the object Student console.log(Object.keys(student)); // [firstName,lastName] We can use the Object.keys() method to check the length of the Object like shown below: // Create Object Student var student = { firstName: "Peter", lastName: "Parker"};// find length of student console.log(Object.keys(student).length); // 2 As you can see, the “object.keys” method returns the length of the object:

 Object.values() method

It works like the Object.keys() method but instead of returning an array of keys it returns an array of values of that object: // Create Object Student var student = { firstName: "Peter", lastName: "Parker"};// get values of student console.log(Object.values(student)); // [Peter, Parker] As you can see, the “object.values” method returns the values of the object:

 Conclusion

An object is something that holds properties and attributes and, it stores key-value pairs. The syntax myObj.methodName() is used to call a method on an object. JavaScript also offers us some built-in methods of the global Object such as Object.create(), Object.values(), Object.keys(). The Object.create() method creates a new object with the specified object prototype, Object.keys() returns an array of the object keys whereas Object.values() returns an array of Object values. In this post, we discuss how to use Object Methods by first calling a user-defined method and then using the built-in methods of global Object.

How to submit a form using JavaScript

JavaScript is a high-level web programming language that is becoming popular day by day. It gives our web pages and web applications the ability to perform certain actions and make them interactive. JavaScript offers forms to web developers that assist developers in collecting data from users and storing that data in a database. When working with numerous apps and websites, form submission is a critical phenomenon. In this post, we will go through how to submit a form using JavaScript in detail but first, we will see how to create an HTML form.

 HTML Form Creation

An HTML form can be created by using the <form> tag that is offered by HTML itself and it takes two attributes: The first is the “action” that contains a URL(which handles the submission of the form process). The second attribute is the “method” that has an HTTP method. An HTTP method can be of various types and the two most commonly used are: GET (used to get some data from a server) POST (used to write data to the server) However, we won’t use these two attributes in this post as we are not working with a server. Let us now write HTML code for form creation: <!DOCTYPE html><html lang="en"><head><title>Submit Form Using JavaScript</title></head><body><form id="myForm"><!-- Input Fields --><input type="text" name="username" id="username" placeholder="Enter your Username"><input type="password" name="password" id="password" placeholder="Enter your Password"><!-- when clicked on the below button, the form will be submitted --><button type="submit">Submit</button></form><script src="code.js"></script></body></html> In the above code, we created a form and gave the id attribute to the form whose significance we will see in a while. Next, we defined two input fields and then defined a button that has a type of submit. In the end, we placed a script tag and referenced the filename “code.js” that will contain our JavaScript code.

 Access Form and retrieve Values from the form

Now that we are done with creating our form, let us access this form from JavaScript and then retrieve the values of username and password that are present inside the form tag. To access the form we will use the id attribute mentioned earlier via the following code: var myForm = document.getElementById('myForm'); In the same manner, we can also get the values from the input fields using the id attribute given in the HTML form. The only difference is that we will give the value at the end of the getElementById so that we can retrieve the value from the input field and not the element itself: var username = document.getElementById('username').value; var password = document.getElementById('password').value;

 Submit Form and Validate Data

To submit the form, we will use the event listener which listens for a specified listener continuously. An event is simply an interaction of HTML and JavaScript triggered by a user or browser when the user manipulates a page and this event is handled by the event listener. var myForm = document.getElementById('myForm');// Event listener that listens for submit event myForm.addEventListener("submit", function(e){ e.preventDefault();// retrieve values var username = document.getElementById('username').value; var password = document.getElementById('password').value;// validate username and password fieldsif(username=='' || password==''){ alert("Please Fill all required fields"); }else{ alert("Form submission successful"); }}) In the above code, first, we get the reference of the form using the id attribute and then initiate an event listener of “submit” on this form. The function specified in the event listener will be invoked once the user clicks on the submit button. Inside the function, we have performed our validation, that is if the input fields of username or password are empty then we will see a message in the alert box saying Please Fill all required fields otherwise we will get the message of Form submission successful. Let us check first by clicking on the submit button leaving the two input fields empty: Let us now fill the two fields and see the output:

 Conclusion

Forms are very helpful in gathering data from users and then manipulating or playing with that data. In this post, we took help from an HTML <form> tag to initialize a form and then went on to define two input fields and a button. Next, we accessed the form element inside a javascript file and then retrieved the values of form input fields using the id attribute. In the end, we answered the question of how to submit a form using JavaScript by initiating an event listener that will listen for the submit event, and whenever a user clicks on the submit button, this event will be fired. We also validated our input fields inside the event listener function.

How To Modify CSS Classes

Any web developer starts their journey by learning HTML, CSS, and JavaScript. HTML gives structure to our webpages, JavaScript is a web programming language that gives us the ability to interact with users whereas CSS gives us the ability to style our web applications and web pages. To manipulate and work with the CSS classes, JavaScript offers us classList and className properties that can be used to manipulate the class attribute. The class name can be used by JavaScript to manipulate the specified element while CSS uses that class name to style that element. Hence, in this post, we will go through how to modify CSS classes but first let us set the environment by initializing elements in HTML and then styling that element in CSS.

 Environment Set up

Let us create a div element that works like a container and place two elements inside this container. One will be the h2 tag and the other will be the p tag. To link the CSS file to this HTML we have inserted a link tag in the head and referenced our CSS file inside the href attribute (style.css): <!DOCTYPE html><html lang="en"><head><title>Modify CSS using JavaScript</title><link rel="stylesheet" href="style.css"></head><body><div class="container"><h2>England</h2><p>The capital of England is London</p></div></body></html> To get the reference of the div element inside CSS, we have used the class attribute. We performed some styling on the div container as well as the elements inside the div container. .container{background-color: rgb(54, 224, 207);}.containerh2, p{color: rgb(125, 104, 184);} The output will look like this:

 Modify CSS Classes

As mentioned in the introductory part of this article, JavaScript offers us classList and className properties that can be used to manipulate the class attribute.The className is used to set a value to a class directly whereas using the classList property we can perform the following functions: classList.add() is used to add class values classList.toggle() is used to turn on or off a class classList.replace() is used to replace a class value with another class value classList.contains() is used to check whether a value exists or not classList.remove() is used to remove a class value Let us go through an example to better understand the classList property and its built-in methods and we will use the same HTML and CSS code that we used earlier. First, let us use the className property to assign a class to the h2 attribute. For that purpose we have referenced a class in CSS that doesn’t exist at the moment and give it some styling shown below: .info{background-color: white;border: 2px solid black;} Next, get the reference of the h2 element using the querySelector(‘h2’) which will select the first h2 element in the HTML code. Next, use the className property to assign the info class to the h2 element. The JavaScript code is given below: // Select first h2 elementconst myh2 = document.querySelector('h2');// Set the info class to myh2 myh2.className = 'info'; To reference this JavaScript code use the script tag with src attribute in the HTML code giving the JavaScript file name in src attribute: <script src="code.js"></script> The code.js is our JavaScript file name. Our web page will now look like this: Let us now modify the CSS classes using the classList property. As seen earlier, the classList property offers us some built-in methods that we can use to modify CSS classes. We will use the classList.add() which will add a class in the following example: // Select the first divconst hideDiv = document.querySelector('div'); hideDiv.classList.add('hidden'); // hidden class added Next, go to the CSS file and initialize the hidden class by making the display none so that the div is not visible: .hidden{display: none;} Now you will see that the div element will be hidden and you will not see anything on your webpage: Let us now use the classList.replace() method where we will replace the existing hidden class with another class wrap. // Select the first divconst hideDiv = document.querySelector('div'); hideDiv.classList.add('hidden'); // hidden class added hideDiv.classList.replace('hidden', 'wrap'); // replace hidden class with info class Next, go to your CSS file and style the wrap class: .wrap{font-size: large;} You will now see that our content is now visible and the font size will be larger than before:

 Conclusion

JavaScript offers us two properties that we can use to modify CSS classes; classList and className property. The className property is used to set a value to a CSS class directly whereas the classList gives us some built-in methods to manipulate the CSS classes. For example, the classList.add() gives us the ability to add class values, classList.remove() gives us the ability to remove a class, classList.toggle() gives us the ability to add toggling to a class and the classList.replace() gives us the ability to replace a class value with another class. In this post, we saw how to modify CSS classes using JavaScript by learning about two properties of JavaScript; classList and className.

How to make an AJAX call?

JavaScript is a high-level programming language where code is executed line by line and is called synchronous execution of code. The disadvantage of synchronous execution is that the next lines of code have to wait for the complete execution of the current line of code. The answer to this problem is asynchronous execution, in asynchronous a statement or a line does not have to wait for the previous code to completely execute rather they can execute in parallel. To achieve asynchronous execution of code, AJAX comes into play. In this post, we will see what AJAX is and how to make an AJAX call with the help of an example.

 What Is AJAX?

AJAX became popular in 2005 when google put it up in their google suggest and it stands for asynchronous JavaScript and XML. XML stands for Extensible Markup Language that is used to encrypt messages which can be read by humans and machines. XML is similar to HTML, but it lets you build and customize your own tags. The function of AJAX is to transmit requests to a server and then receive data from that server in an asynchronous fashion. The advantage of AJAX is that it performs its function without the need of refreshing the whole page. For example, when you type something to search for in the google search bar, with every key press the search bar makes AJAX calls and the user receives suggestions without actually refreshing the page. It should be noted that the AJAX communicates with the server using the XMLHttpRequest object, JavaScript/DOM to make requests, and XML as a data transmission mechanism. AJAX is triggered with an event and then performs its functionality by first creating an XMLHttpRequest object and then sending the HttpRequest to the server where the HttpRequest is processed and a response is generated which is then sent back to the browser with some data. The browser processes the returned data and updates the page content using JavaScript. Now that we know what AJAX is and how to make an AJAX call using JavaScript.

 AJAX Call using JavaScript

In this example, we will first initialize the XMLHttpRequest object which is used to communicate with the server or to put it simply, make an AJAX call. The XMLHttpRequest has many built-in methods that we can use to manipulate or play with the server by sending, interrupting responses, and receiving data from the server. We will connect to a free fake API to test our AJAX call. The link of the API we are going to use is given below: https://jsonplaceholder.typicode.com/ The complete code to make an AJAX call is given below: functionmyFunc() {// Initializing XMLHttpRequest object varxhttp = newXMLHttpRequest();// Establish connection with fake API varurl = 'https://jsonplaceholder.typicode.com/todos/1';// get api from url xhttp.open("GET", url, true);// When the request is successful the below function will execute xhttp.onreadystatechange = function () {// if request is complete and succesfulif (this.readyState == 4&&this.status == 200) { console.log(this.responseText); } }// Send Request xhttp.send();}// call myFunc function myFunc(); In the above code, first, we initialized a function with the name of myFunc(), and inside this function, we created an XMLHttpRequest object. Next, we establish the connection with an API using a URL. To get the API we use the xhttp.open() method and pass the HTTP method GET and the URL. The get method is used when we are getting some data from a server and the POST method is used when we are writing or updating data on the server. Now when the request will finish executing and if it’s successful, the onreadystatechange event will execute where we are using a condition that if the request is complete and the request was successful, console log the data. The status code 200 is used which means ok. The 400 status code means error and the 300 status code means redirecting to some page. The next step is to send the request using the send() method. In the end, we call the myFunc() function and we will see the following output in the console log: The status code seen in the developer tools is 200 which means ok:

 Conclusion

AJAX stands for asynchronous JavaScript and XML where XML is used to encrypt messages that are made in readable format for humans and machines except that XML lets you customize your own tags. AJAX allows you to transmit data to the server without having to refresh the entire page. It performs its operation asynchronously hence improving speed as the code does not have to wait for the previous code to complete its execution., the XMLHttpRequest object is used to make an AJAX call. In this post, first, we discussed what AJAX is and then went on to discuss how to make an AJAX call using the XMLHttpRequest object.

How to make a Discord Bot with JavaScript

Discord has continuously demonstrated over the last five years that it is the instant messaging tool of choice for not only gamers, but anyone wishing to talk, video chat, or broadcast with their friends online. Discord Bots perform a number of useful tasks that are automatic using AI(artificial intelligence). For example, welcoming a new user, moderating content, and blocking or banning someone that breaks the rules of your discord server. Discord bots are very useful as they can help you with almost everything from automating menial activities to starting to play music across your server and in this post, we will show you how to make a Discord Bot with JavaScript.

 Bot Registration

The first step is to register or make an account on the Discord server by going to the below-mentioned URL: https://discord.com/register?redirect_to=%2Fdevelopers%2Fapplications You will see the following screen where you have to register by filling the text fields accordingly and once done click on the continue button: If you already have an account then simply log in to your account. Once you are logged into your Discord account, go to the below URL: https://discord.com/developers/applications Click on the New Application which is located in the top right corner of the viewscreen: You will be asked to name your application. In my case, I have named it as technicalWriter: Click on Create and you will be redirected to your created application dashboard. On your app dashboard click on the Bot and then click on Add Bot button to enable your app as a bot: You will see that your bot has been created: The next step is to copy the token and paste it somewhere where you have access to it, as we will use this token later in our VScode editor(or any other editor of your choice) to connect to the JavaScript bot:

 Addition of the bot to the server

Now that we are done with the bot registration, let us take the next step which is to add the bot to the server. For this purpose, we have to create a new Discord server so that we can install the bot there. To create a new Discord go to the following URL which is the homepage of the Discord server: https://discord.com/channels/@me Next, click on the Plus icon present on the left as shown below: You will see Create a Server window on your screen where you have to click on the Create my own option as shown below: Next, you will be asked to give a name to your server. In our case we have chosen the name technicalWriter: Once done you will see your server on the left side of the screen: Once done, go back to the Discord Developer Portal: https://discord.com/developers/applications In the app dashboard, click on OAuth2 and then select the bot which is located under the Scopes section: When you select bot you will see the bot permissions where you have to select all the permissions that you want for your bot. We chose the send messages and read message history as shown below: A URL has been generated in the below text field. Copy this URL by clicking on the copy button and then paste the copied URL on a new tab: Once done, you will be redirected to the following page where you will install the bot to your preferred Discord Serve by choosing the server you created before. I created technicalWriter so I will select that and then will click on the Authorize button: When you click on the continue button you will see the confirmation screen where you have to click on the authorize button: After clicking on the Authorize button you will see the following screen: Close the tab and let us now move towards the installation of discord in our IDE.

 Installation of DiscordJS library in IDE

Now that we are done with registering our bot let us install it in our IDE which is visual studio code. Create a new folder with the name of “test” and go to the terminal of Visual studio code and execute the below command to change the directory to the directory we just created: $ cd test The test is the folder we created: $ npm init -y Now run the above command which will initialize NPM and create a package.json file in the test directory: Let’s install Discord.js with the below-given command: $ npm i discord.js The next step is to install a nodemon that is used for automatic restarting of our server: $ npm i nodemon We have successfully installed all the dependencies that are required to create a discord bot.

 Bot start Command

Now that we are done with registering our bot and installing all the dependencies let us create an index.js file in our test directory. Index.js file will act as our starting page or homepage of our application. Open the package.json file seen in the above screenshot and add the below script so that we are able to run our file: "scripts": {"start": "node index.js","dev": "nodemon index.js","test": "echo "Error: no test specified" && exit 1" }, Now we will be able to run our application with the command of npm run start and can start the development server with npm run dev command.

 Writing test Bot

Now that our development environment is ready let us start writing the discord test bot. We will implement a very simple test bot so that we can confirm it works. Open index.js created earlier and paste the below-given code: // importing discord and its relevant classesconst { Client, Intents } = require('discord.js');// Instantiate a new clientconst client = new Client( { intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });// listening for event to notify progress client.on('ready', () => { console.log("Connected as " + client.user.tag);})// paste your bot secret token here bot_secret_token = "XXXXXXXXXXX"; client.login(bot_secret_token); We are importing the discord js library first and then creating an instance of the client so that we can connect to Discord. After that, we used the event .on() where the ready event is called whenever the bot is ready to be used. When the ready event is called, the callback function within .on() will start executing. In the end, we have provided our bot secret token. It should be noted that you have to replace the bot_secret_token with the bot token of your account and you will have to keep it as a secret because it is like the password of your bot. To find the secret token of your bot click on the below URL: https://discord.com/developers/applications/ After going to the above URL, go to the Bot section present on the left and then click on reveal token. Copy the revealed token and replace it with the bot_secret_token in the above code. Once done, run your application by going to the terminal and executing the below command: $ nodemon index The output should say Connected as if you were successful in creating your first test bot:

 Discord Bot

We are now ready to create our discord bot that will give a reply to our message. We have done all the hard work and now we just needed to add a few more lines to the already existing code of JavaScript. Copy or type the below code to your JavaScript code: // listen to server chat// reply if the message received is Hello discordbot! client.on('message', function(mesg){if(mesg.content === "Hello discordbot!"){ mesg.reply("Hello yourself!") } }) The complete code is given below: // importing discord and its relevant classesconst { Client, Intents } = require('discord.js');// Instantiate a new client with some necessary parameters.const client = new Client( { intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });// listening for event to notify progress client.on('ready', () => { console.log("Connected as " + client.user.tag);})// listen to server chat// reply if the message received is Hello discordbot! client.on('message', function(mesg){if(mesg.content === "Hello discordbot!"){ mesg.reply("Hello yourself!") } })// paste your bot secret token here bot_secret_token = "XXXXXXXXXXX"; client.login(bot_secret_token); The above code will ensure that the bot will continuously listen for any received messages. If the received message has Hello discordbot! then the bot will send a message in the channel as a reply and the reply message will be Hello yourself!. To check the functionality go to your discord account and select the server you have created (in our case it was technicalWriter). Now send a message Hello discordbot! in the general text channel and you will see the following output: Congratulations! We have successfully created a discord bot that reads a message and then replies to that message automatically.

 Conclusion

Discord bots are very useful as they can perform numerous automatic tasks for example welcoming a new user on your discord server or replying to a user using artificial intelligence and much more. In this post, we discussed how to make a discord bot using JavaScript by first registering our bot and then installing our bot to the server. After that, we performed the installation of the bot server in our IDE that was visual studio code and then went on to code a simple test bot that showed who logged in. After that, we created a discord bot that replies with a message whenever the server gets Hello discordbot! Message.

Iterate Array Items using .map() method

JavaScript is one of the most known scripting languages that offer Arrays to store different elements under the same name. There are different methods available through which we can iterate over Arrays for example for loop, while loop, forEach method, and much more but the most common among all these is the map() method. This write-up explains how to iterate through array items using the .map() method.

 What is the map() method?

The map() method is a built-in array method that iterates through the array and performs a function on each element in the array. The original array remains the same as this function returns a new array with the same length. It should also be noted that the map() method does not execute for an empty array.

 Syntax of map() method:

myArray.map((value,index,array)=>{return;}); The map method has a callback function (the asynchronous equivalent of a function) that accepts three parameters: Value: It is the current value or element of the array Index: It is the current index of the array element on which the function is executing. Array: It is the target array.

 Example 1

In this example, we will iterate through an array by multiplying each element of the array with 2: // an array constmyNumbers = [4, 8, 9, 15, 20];// multiply each element of array with 2 constmultipliedWithTwo = myNumbers.map((value)=>{return value*2;});// display the returned array console.log(multipliedWithTwo); In the above code first, we initialized an array and then applied the map() method on the original array. Inside the function, we returned the value multiplied by two. It should be noted that index and array parameters can be omitted when you don’t want to use them. The resultant array is stored in multipliedWithTwo variable and then we displayed this variable using the console.log() method. We can see in the above output that every element of the original array is multiplied by 2 and we got our desired result. When the operation you are performing on each element is of one line of code then the simpler and cleaner way of implementing the map() method is used which is given below: // an array constmyNumbers = [4, 8, 9, 15, 20];// multiply each element of array with 2 constmultipliedWithTwo = myNumbers.map((value)=>value*2);// display the returned array console.log(multipliedWithTwo); There are no curly brackets and return. The output is still the same as seen in the above screenshot.

 Example 2

Let’s look at another example where will iterate through an array of strings: // an array constfirstNames = ["Super", "Bat", "Spider", "Iron"];// add man with each string in the array constheroesNames = firstNames.map((value)=>value+"man");// display the returned array console.log(heroesNames); In the above code, first, we initialized an array with the first names of the famous superheroes. Then we applied the map() method on that array where we concatenated the string “man” with every element of the firstNames array. In the end, we displayed the returned array from the map() method using the console.log() method: We can see that with every element man has been concatenated.

 Conclusion

To iterate over an array JavaScript offers us a variety of techniques including loops and the forEach() method. However, the most famous iteration technique is the map() method. The map() method executes for each array’s element and returns a fresh array that has the length exactly equal to the original array. This post explains how to iterate through an array using the map() method along with two examples.

How to create an HTML element through JavaScript using createElement()

HTML is a markup language that gives structure to our web pages whereas JavaScript is a web programming language that offers interactivity with the user. Mostly, for simplicity, developers define and create elements inside HTML. However, it is not the only way to create elements and we can also create elements using the JavaScript document object method createElement() to make our webpage more dynamic. Due to the document object, we can access HTML elements.

 What is createElement()?

The createElement() is a document object built-in method that has the function of dynamically creating an HTML element from and returning the newly created HTML element. The syntax of createElement() is given below: var creatingElement = document.createElement(HTMLTagName); The createElement() takes one parameter HTMLTagName which is a mandatory parameter of type string and it is the tag name of an HTML element. It should be noted that the createElement() method does create an HTML element however to attach the element to the document (webpage) we have to use the appendChild() or insertBefore() methods. Now that we know what the createElement() method is, let us look at an example to better understand the createElement() method.

 Example1:

In this example, we will create a button element from JavaScript at the click of an already existing button. Let’s first create a button in HTML that has an onclick event attached to it. <body><button onclick = "myFunc()">Magic Button</button><script src="code.js"></script></body> Whenever a user will click on the button, it will start executing the myFunc() function. In the end, we have used the script tag and provided the source (code.js) of the JavaScript file that contains the myFunc() function. The JavaScript code is given below: function myFunc() { var myBtn = document.createElement("button"); myBtn.innerHTML = "New Button"; document.body.appendChild(myBtn);} In the above code, first, we initialized the myFunc() function and then created a button element using the createElement() method. Then to give the button a title we used the myBtn.innerHTML property. In the end, we attached the button to the body of our HTML using the appendChild() method. The output is given below: We can see that whenever we click on the Magic button, it creates a new button with the title “New Button”.

 Example2:

In this example, we will create an h2 tag of HTML through javascript and then attach it with the HTML body using the insertBefore() method. For this purpose, let us first write the HTML code: <body><div id="myContainer"><p id = "para">Insert Heading above this</p></div><button onclick = "myFunc()">Magic Button</button><script src="code.js"></script></body> The rest of the code is the same as example 1 with the exception that now we have created a div element inside which we created a <p> tag with the id “para”. The JavaScript code is given below: function myFunc() { var myContainer = document.getElementById("myContainer"); var para = document.getElementById("para"); var myHeading = document.createElement("h2"); myHeading.innerHTML = "New Heading"; myContainer.insertBefore(myHeading , para);} Inside the function, we first get the reference of the <div> and <p> element of HTML. Then we create an <h2> element using createElement() method. To insert it before the <p> element we use the insertBefore() method where we pass the newly created <h2> tag and the <p> tag reference as parameters. The output of the above code is given below: Whenever we click on the Magic Button, a new element h2 is created via JavaScript’s createElement() method.

 Conclusion

The document object gives us access to HTML elements and one of the built-in methods of the document objects is the createElement() method. The createElement() method is used to create an HTML element dynamically by taking the HTML tag name as its parameter and then returning the newly created HTML element. To attach the newly created HTML element to HTML we use the appendChild() or insertBefore() methods. In this post, we saw how to create an HTML element using the createElement() method.

How to convert Map keys to an array?

JavaScript is a high-level programming language that offers its developers many different data structures which are used for storing data and content and can be easily maintained and understood. The most commonly used structures for storing collections of data are arrays and objects. Arrays are used to store indexed records while in objects key-value pairs are stored. In 2015, JavaScript introduced another iterable object known as the map in ECMAScript whose main purpose was to give developers more flexibility. In this post, we will discuss what a map object is and how to convert map keys to an array.

 Map Object

A map object is a simple object whose function is to store a collection of elements with the exception that the map stores data in key-value pairs. Whatever order you insert data in the map object, it remembers that order. The syntax of the map object is given below: var map = new Map([iterableObject]); The iterableObject argument is optional and is the object whose elements are stored as key-value pairs in the map object. Let’s implement a map object so that we know how the map object is initialized and how it works: // create map var map = newMap();// set up keys and values for map object map.set('1', 'string'); // key as string map.set(1, 'number'); // key as numeric map.set(true, 'boolean'); // key as boolean// get values from map using keys console.log( map.get(1)); // number console.log( map.get('1') ); // string In the above code, we initialized a map object and then set some values inside the initialized map object. After this, we fetch a value using the map.get() method and display it using console.log():

 Conversion of map keys to array

We can get the keys of the map object using the Map.keys() method. To convert the map keys to an array we can use two methods. The first approach will be to use the Array.from method which helps in converting a MapIterator (an object helping us to loop through records or collections) into an array in the following manner: // create map var map = newMap();// set up keys and values for map object map.set('fruit', 'apple'); map.set('quantity', 20); // convert map keys to array let keys = Array.from( map.keys() ); console.log(keys); // [fruit, quantity] In the above code, first, we initialized the map object and then set two values for the map object. Next to get keys of the map object we used the built-in method of map object map.keys(). Then we used the Array.from method which will convert the result into an array. In the end, we displayed the keys onto the console using the console.log() method. The second approach we can take is to use the spread operator “…” whose function is to take an iterable and then convert that iterable into individual elements. // create map var map = newMap();// set up keys and values for map object map.set('fruit', 'apple'); map.set('quantity', 20); // convert map keys to array let keys =[ ...map.keys() ]; console.log(keys); // [fruit, quantity] The code given above remains the same with the exception of the usage of spread operator “…”. As you can see in the output that we have successfully converted our map object into an iterable array:

 Conclusion

JavaScript introduced a map object in ECMAScript in 2005 in which we can store a collection of elements in key-value pairs. We can get the keys from the map object using the built-in method map.keys(). To convert map keys to an array we have to first initialize a map object, followed by using the map.keys() method and then use the spread operator or array.from() method to convert the keys into an array. In this post, we discussed what a JavaScript map object is and how to convert a map object to an array using two approaches; using the spread operator and using an array.from() method.

JavaScript setInterval() and setTimeout() methods Explained

JavaScript is a high-level web programming language in which every statement of code is executed line by line. However, suppose you want to execute some code or function at a later stage(in the future) and not immediately. This is called scheduling a call and can be achieved with the two built-in methods; setTimeout() and setInterval(). This post discusses what setInterval() and setTimeout() built-in methods are. However, before we go any further it should be noted that these two methods are not part of JavaScript specification and are part of HTML standard specification but are supported in all the major browsers.

 What is the setTimeout() Method?

The setTimeout() method is used to run a specific code in the future and not immediately by calling a callback function after a specific time interval. The callback function is defined as the function provided to another function as an argument and executed in the outer function later.

 Syntax of setTimeout() Method

The syntax of setTimeout() is given below: setTimeout(callbackFunc, milliseconds); The first argument that we give to the setTimeout() method is the callback function which is executed after the provided milliseconds. Example Let us go through an example where we will set the setTimeout() method on a button and when the user clicks that button, the callback functions will be executed after 2 seconds: <!DOCTYPE html><html lang="en"><head> <title>setTimeout()</title></head><body> <!-- Initialize a button with the setTimeout method --> <button onclick="setTimeout(myFunction, 3000)">Try it</button><!-- JavaScript code inside the script tag --> <script> function myFunction() { alert('Hello'); } </script></body></html> In the callback function, we initialized an alert that will show after two seconds with the message hello.

 What is the setInterval() Method?

The setInterval() method is the same as setTimeout() as it also executes a callback function after a specific time but with the exception that it executes the callback function continuously after that specific interval of time.

 Syntax of setInterval() Method

The syntax of the setInterval() method is as follows: setInterval(myfunc, milliseconds); Like setTimeout() the first argument is the callback function which will be executed after the specified number of milliseconds and the execution will be repeated continuously after this specific time. Example Let us go through an example where we will show the current system time after every 1 second. const myFunc=()=> { const d = new Date(); console.log(d.toLocaleTimeString());} setInterval(myFunc, 1000); In the above code, we first created a function in which we created a new date using the Date object and console logged the system time. After defining the function, we used the setInterval() method, passed the function name, and 1000 milliseconds which is 1 second. Now the function will run after every 1 second and we will see our system time on the console log after every second:

 Execution stoppage of setTimeout() and setInterval()

If you don’t want the callback function of setInterval() or setTimeout() to execute anymore, we can use the stopping methods available for both of them. clearTimeout() Method To stop the execution of the setTimeout() function we can use the clearTimeout() method which will take a variable/id that is returned from the setTimeout() method as an argument. Example In this example, we will stop the execution of the call back function defined with the setTimeout() method: <!DOCTYPE html><html><head> <title>clearTimeout()</title></head><body> <!-- Initialize a button with the setTimeout method --> <button onclick="myFunc()">Try it</button> <button onclick="stop()">Stop</button> <!-- JavaScript code inside the script tag --> <script> var t; // function to invoke setTimeout() function myFunc() { t=setTimeout(myFunction, 3000); } // function that will be invoked after 3 seconds function myFunction(){ alert("Hello"); } // function for stopping the setTimeout() function stop() { clearTimeout(t); } </script></body></html> The above code shown is an extended form of the setTimeout() example shown previously. In this code, we added another button with the name of Stop and invoked the stop() function whenever a user clicks the stop button. The stop() function has clearTimeout() that has a variable t as argument. The variable t is simply an id returned from the setTimeout() function. When a user clicks on the Try it button then after three seconds we see Hello in the alert as seen previously. However, if the user now clicks the stop button before 3 seconds then the call back function myFunction will not be invoked and hence we won’t see an alert. This phenomenon is shown below: clearInterval() Method Similarly, to stop the execution of the setInterval() function, we can use the clearInterval() method that will also take the variable returned from the setInterval() as an argument.

 Example

Let us go through an example where we will stop the execution of the callback function of the setInterval() method. <!DOCTYPE html><html lang="en"><head> <title>Document</title></head><body><button onclick="clearInterval(myVariable)">Stop time</button> <script> var myVariable = setInterval(myFunc, 1000); function myFunc() { const d = new Date(); console.log(d.toLocaleTimeString()); } </script></body></html> In the above code, we defined a button in the HTML and then initialized the onclick event on this button. When the user clicks on the defined button, the setInterval() method will stop executing. When we clicked on the “Stop time” button, the system time stopped displaying on our console log:

 Conclusion

The setTimeout() and setInterval() methods both schedule a call that is to execute a function later after a specified number of milliseconds with the exception that setInterval() executes a function continuously after that specific time, unlike setTimeout() method which executes a function only once after the specified time. In this post, we discussed what the setTimeout() and setInterval() method is and we saw their examples along with screenshots of the output. In the end, we also saw how to stop the execution of the callback functions associated with setTimeout() and setInterval() methods.

JavaScript replaceWith() method| Explained with Examples

JavaScript updates come with new and improved methods and features. One of these new features is the replaceWith() method. JavaScript is supported on all web browsers and most of the functions or methods of JavaScript are all functional on these browsers with the exception of Internet explorer. JavaScript is famous for coming up with new and more efficient solutions to various problems. The replaceWith() is exactly that, a new method that is far better than the trivial approach

 What is replaceWith() method

The replaceWith() method is used to replace an element\node from the DOM (Document Object Model) with another element\node. Now, you may as well think why do we need a separate method to a task that can easily be done using the traditional JavaScript approach. Well, to put it in simple words, the replaceWith() methods allow the users to replace elements by directly referencing the child nodes. Previously, we had to refer to the parent node and then refer to the child node to replace the child node. The replaceWith() method is supported by all modern web browsers except Internet Explorer. You can get the support for Internet Explorer but then you will require a Polyfill. Syntax The syntax of replaceWith() method is as follows: oldNode.replaceWith(newNode); oldNode: The element or the node that is to be replacednewNode: The node or element that will replace the old node You can also append multiple nodes using the replaceWith() method like so: oldNode.replaceWith(newNode1,newNode2,newNode3....); Now, we know the syntax of the replaceWith() method, we know what it is supposed to do, but we still don’t know how to use it. So, let’s try using it with an example. Example Create an HTML File with the following lines inside the <body> tag. <center> <h1>LinuxHint Tutorial</h1> <code>replaceWith() method</code> <div id="demo"> <p>This is a random text to be replaced</p> </div> <button id="btn">Click To Replace Node</button></center> Let’s go over the code snippet and explain a few things: We created a “center” tag and placed everything inside of it to center it on the page. We created a “div” with the id “demo”. Inside the div, we have a “p” tag with some text inside it. We created a button outside the div to replace the text inside the p tag on the click of this button and linked it to the function “btnClick()”. Let’s run the HTML page and this is how it looks: Let’s create the JavaScript part of the tutorial. First, we create the function “btnClick()”, under the script tag or in a different script file. function btnClick() { // put the later commands inside here} To change the <p> tag or its child nodes, we first need to get its reference as soon as the button is pressed. To get the reference of the <p> tag which is inside the <div> tag, we use a query selector. Since the div has the id = “demo” we use the following command: const pTag = document.querySelector("#demo p"); Now we need an element that will replace the <p> tag. So, let’s create an input element and then give it some value, like: const newInput = document.createElement("input"); newInput.value = "Replaced the Old Node"; Now that we have created an element to replace the tag with, let’s actually replace it using the replaceWith() method by using the following code snippet: pTag.replaceWith(newInput); Lastly, if we want to remove the button as well from the screen. To do that use: const btn = document.getElementById("btn"); btn.remove(); The complete code snippet would look like this: function btnClick() { const pTag = document.querySelector("#demo p"); const newInput = document.createElement("input"); newInput.value = "Replaced the Old Node"; pTag.replaceWith(newInput); const btn = document.getElementById("btn"); btn.remove();} Run the HTML file and you will see this result: Now to check if the <p> tag was actually replaced we can do that by checking the source code with the developer tools. At first, it’s like this: After clicking the Button it becomes like this: As you can see, the <p> tag gets entirely replaced with the <input> tag, when we press the button and now there is only the input tag inside the “#demo div”.

 Appending multiple nodes

We can also use the replaceWith() method to insert multiple nodes in replacement for the old node. Separate multiple nodes with a comma “, ”. In the current example, let’s try to add a simple text node along with the Input tag by using the command: pTag.replaceWith(newInput, "Hello"); Note: If we only write a string, it will automatically create a text node. Output:

 Replacing only childNodes with replaceWith() method

One of the main features of replaceWith() is to replace the childNodes directly. Suppose, we don’t want to entirely remove the <p> tag from the above example. Maybe, we want to remove the content inside the <p> tag and insert a <b> bold tag with some text in the <p> tag. We can do that by referencing the childNodes of the <p> tag. First, let’s create the bold tag <b> with: const newChildNode = document.createElement("b"); newChildNode.textContent = "I am a bold tag and the new childNode"; Now, let’s replace the first child node of the tag by using the array syntax like: pTag.childNodes[0].replaceWith(newChildNode); Run the code and the output is as follows: Let’s examine the source code from the developer tools option of the browser to check that the <p> wasn’t entirely removed rather than the bold tag and its content was added inside the <p> tag as its child nodes. Now, as you can clearly see, we have successfully replaced the child node of the <p> tag and added another tag <b> inside it as its child node. That’s it for the replaceWith() method.

 Conclusion

The replaceWith() is a really useful method that can be used to replace nodes and elements with new nodes and elements. This approach is definitely better than the traditional JavaScript approach of referring to the child node by using the reference of the parent node, this means we need to get the reference of the parent node as well. We learned the syntax and working of the replaceWith() method along with examples and confirmed the replacement by looking at the source code inside the browser’s developer tools.

JavaScript Objects Explained

JavaScript objects are the implementation of the real-world object in a programming language, everything is an object. JavaScript is a programming language that is often mistaken for being a class-based programming language but in reality, it is an object-based programming language. Objects are used to mimic the behavior of real-world objects; for instance, a fruit has its properties like the name, color, shape, taste, and season. you can define this entity “fruit” against its key-value pairs, Keys being the properties and values being actual values of that property. A fruit object. fruit = { name : "Apple", shape: "Circular", taste: "Mostly sweet but also bitter", season: "All seasons"} You differentiate a key and value by putting a colon “:” in between them, and you put a comma in between different key-value pairs. This pattern or structure of defining a real-world entity is similar to a JSON object and this is because the JSON is based on the JavaScript object definition.

 JavaScript Objects and properties

Creating or defining an object can be done in two ways: By using the “new” keyword By using the curly “{ }” to enclose the key-value pairs

 Creating a JS object by using the new keyword

The “new” keyword means to create a new instance of an object’s constructor. To create an object using the “new” keyword, you create a variable and then put it equal to the object constructor with the “new” keyword; and add key-value pairs by using the “dot-operator”. Syntax variableName = new Object(); // Creates an instance of the object variableName.propertyName = propertyValue;//Gives a key-value pair to the object You can create an object of a person having the properties: first name, last name, age, and job with the following lines of code: var person = new Object(); person.firstName = "John"; person.lastName = "Doe"; person.age = 27; person.job = "Auditor"; The first statement creates a variable with the identifier “person” and calls the object() constructor by using the “new” keyword. The next four statements are used to set 4 properties or “key-value” pairs of the object. The property name is written with the identifier of the object by using a “dot-operator”, and the value of the operator is given after the assignment operator “=”. You can print this object that you have just created by using the following statement: console.log(person); Upon executing the code, you will get the output: The object is printed onto the console and you can see the key-value pairs clearly.

 Creating a JS Object using curly brackets { }

One other way of creating JavaScript is to create a variable and set it equal to key-value pairs (which are enclosed inside the curly braces) directly, this is known as defining an object using the literal-object syntax. Syntax variableName = { propertyName : propertyValue }; You can create the same person object with the same properties by using the literal syntax: var person = { firstName: "John", lastName: "Doe", age: 27, job: "Auditor",}; You are setting the variable “person” equal to key-value pairs which are enclosed inside curly braces {}. Each key-value pair is separated by a comma “,” keys and values are separated by a colon “:” You can print this object’s key-value pair on the console with the following commands. console.log(person); When you executed this code snippet you see the following output: You can see the key-value pairs on the console, the string values are enclosed inside the quotation marks, and integer values are not enclosed by anything.

 Fetching Values from object properties

You can get values from the object property by using two ways: One is to use the simple dot syntax: objectName.propertyName; The second way is to use the array accessing syntax like: objectName["propertyName"]; Take the person object from the above examples which we created with the following code: var person = { firstName: "John", lastName: "Doe", age: 27, job: "Auditor",}; We can access its properties using both of the following ways: console.log(person.firstName); console.log(person["lastName"]); The first statement accesses the value using the dot-operator; the second statement accesses the value by using the array methods, the output of the code would be: That’s all about JavaScript objects.

 Conclusion

Real-world entities can all be represented Programming Language along with their properties by using the Objects, which defines an entity’s properties by using a key-value pair. We learned how an Object works, how to create an object using different methods, and how to fetch data from an object with the help of examples in which we converted a real-world object into a programming language object.

JavaScript Input Checkbox checked Property | Explained with examples

JavaScript can be used to manipulate the behavior of HTML elements of a page. One of the most commonly used elements would be the input tag <input>. The input is used to create an interactive User Interface (UI) with the purpose of taking information from the user. The input tag has various types. Some of these types include a button, image, checkbox, radio-box, and so on. Other than types, there are various attributes of the input tag <input>. These attributes are compatible with certain types, for example, the checked attribute is not compatible with button type as it is only compatible with a checkbox or a radio button.

 Checkbox and checked property

When you create a form for taking information from the user, quite often you are using an input type called a checkbox. This checkbox takes advantage of one attribute only and that is the checked attribute\property. Very briefly, we are going to see how this checkbox works, and then we are going to manipulate it properly using javascript. Let’s start by displaying a simple checkbox in an HTML page. Use the following code for creating a checkbox: <input type="checkbox" name="cBox" id="cBox" /> This is a Check box As you can see, we created an input tag <input> and gave it a name and id, and the text to display next to it. The full code snippet for better demonstration would go like this: <center> <h1>LinuxHint Tutorial</h1> <code>Checkbox Checked Property Manipulation Using JavaScript</code> <br /> <input type="checkbox" name="cBox" id="cBox" /> This is a Check box <br /></center> The output is: As we can see, we have a checkbox being displayed on the screen. Let’s add the “checked” property so that the checkbox is already marked when the page loads. For adding the “checked” property, use the following line in your code: <input type="checkbox" name="cBox" id="cBox" checked/> This is a Check box We can confirm this by even going to the browser’s developer tools and then into the properties tab, where we can see the property “checked” and its value like: We can change the checked property by clicking on the checkbox itself, like: But what if we want to use JavaScript to manipulate the checked property.

 How to change checked property using JavaScript

To use JavaScript to alter elements on the HTML we are going to create a trigger. A trigger can be anything, it can be an event, or mouse-location, or a button. We will require two buttons. One of which will change the “checked” property’s value to true, and the other one to change it to “false” Let’s first create the two buttons using the following lines. <button id="chkBtn" onclick="checkBtnClick()">Check</button><button id="unchkBtn" onclick="uncheckBtnClick()">Uncheck</button> These lines would create the two buttons on the screen as: Time to bind these buttons with the functions that we have defined inside the “onclick” property. To create these two functions, use the following commands inside the script tag <script>. <script>function checkBtnClick() { document.getElementById("cBox").checked = true; }function uncheckBtnClick() { document.getElementById("cBox").checked = false; }</script> Run the file again and click on these buttons to examine the behavior of the checkbox. You will have this behavior. As you can see, we are now changing the checked property’s value of the checkbox using JavaScript.

 Conclusion

Javascript can be used to manipulate the value of the “checked” property of a checkbox inside the <input> tag. HTML elements are often manipulated using JavaScript, and these manipulations are often done as a result of some action, maybe after the user presses a button or clicks somewhere on the screen. We briefly went through what checkboxes are, how to create them, what is their “checked” property and how to manipulate that property when the user presses a button using JavaScript.

JavaScript Global, Function, and Block Scope | Explained

JavaScript is pretty renowned in the current programming market, and that is due to its vast usage. Becoming a JavaScript developer is not only a good job but it is now essential to survive in the programming market. Javascript, just like any other programming language, depends on the use of variables. And each variable has its own scope. In programming, the scope is defined as the accessibility of the variable. Or in more technical terms, it is the reference to the context of the code. So, how can we differentiate between the scope of the variables, and on what factors does this “scope” depend? Well, we are going to cover everything related to variable scope.

 Variable Scope

In JavaScript, there are 3 types of variable scope, namely: Global Scope Function Scope Block Scope Although, there used to be only two types of scopes before ES6, the global scope, and the local scope. But, with ES6 local scope was broken down into function scope and block scope. Let’s start with the global scope first.

 Global Scope

The variables defined outside of any function or curly brackets are known as global variables and have global scope. Global scope means that the variables can be accessed from any part of that program, any function or conditional state can access that variable. For example var name = "linuxHint";function printName(){// the variable can be accessed inside here console.log("This tutorial is by "+name);} printName(); Output Note: It is not a good practice to use global variables when they are not needed as every code block will have access to those variables.

 Local Scope

If you were to define some variables inside curly brackets {} or inside a specific function then those variables are called local variables The local variables have a very confined scope which is called the local scope But, with the release of ES6, the local scope was further broken down into two different scopes: Function scope Block scope.

 Function Scope

The function scope is the accessibility of the variables defined inside a function, these variables cannot be accessed from any other function or even outside the function in the main file. For example First, we created a variable inside a function and accessed it inside the function: function abc() { year = 2021;// the "year" variable can be accessed inside this function console.log("The year is "+ Year);}// the "year" variable cannot be accessed outside here abc(); Output You can see in the output that it is working perfectly fine as expected. However, if we try to access this variable outside of the function then we get an error: function abc() { year = 2021;// the "year" variable can be accessed inside this function}// the "year" variable cannot be accessed outside here console.log("The year is "+ Year); abc();

 Block Scope

Block scope is also a sub-type of local scope. The block scope can be defined as the scope of the variables inside the curly brackets {}. Now, these curly brackets can be of loops, or conditional statements, or something else. You are only allowed to refer to these variables from within the curly brackets {}. Imagine a nested situation: A block of code enclosed with curly brackets{} containing some block variables. { let a = 10; const b = 5;} This block of code is itself inside a function. function addition() { { let a = 10; const b = 5; }} Now when we try to access the variables from inside the function but outside of that specific block. function addition() { { let a = 10; const b = 5; } console.log(a + b);} And to access this function we need to invoke it by: addition(); Then we’ll be met with an error, even though they are local variables of the same function. The keywords let and const are used to define block variables. For Example The following checks the marks obtained by a student and shows whether the student passed or failed. marksObtained = 60if(marksObtained >= 45){ let status = "Passed"; console.log("Subject Remarks: " + status);}else{ let status = "Failed"; console.log("Subject Remarks: " + status);} We created a block-scoped local variable enclosed within curly brackets {} by using the keyword let. We can even replace this let with the const. The output is as: If you are trying to refer to the local variable from outside the function you will get an error “status(variable name) is not defined”: Note: To refer to the “status” variable, we are calling the console.log() function from outside the conditional brackets;

 Importance of let and const keyword while declaring block variables

If you declare a variable inside curly brackets{} without using the let and the const keywords then the variable will be declared as a “Global variable”. This is due to the fact keywords have their scopes predefined. To learn more about variable declaring keywords. To show this, we are going to remove the let keyword from the above code snippet and run the code. As you can clearly see, we were able to access this variable outside of the curly brackets {}, which means that the variable without the “let” and “const” keywords gets defined with a global scope.

 Conclusion

Variables are “the most essential” part of a programming language. Variables have different scopes depending upon how they are declared., a variable can be one of three different scopes, global, local, and block. We have learned how these variable scopes work by going over multiple examples, we even encountered errors when trying to access variables with different scopes.

JavaScript Function closures | Explained

After the arrival of the ES6 version of JavaScript, there are still a lot of features that are rather confusing to the masses. JavaScript is widely known to have a solution to every problem, and implementation of most (if not all) concepts. One of such concepts is the concept of Closures The concept of closures has been around for quite some time now, but people have difficulty understanding it. We are going to go over step by step and make it really easy to understand with the help of examples.

 What are Closures

Very briefly, Closure is having access to the outer scope from the inner scope when working with nested functions. A closure is created every time a nested function is executed. The variables defined inside the function are created on function execution and are removed from the memory upon the complete execution of the respective function. To understand the concept of Closures we need to know the difference between the global scope and the local scope. Well, we are going to go over these really briefly.

 Scopes of Variable

As mentioned above, there are two major variable scopes: Global scope Local scope The variables defined outside of any function are known as global variables and have a global scope. These variables can be accessed from anywhere inside the program, that is why we use the term “global”. Comparatively, the variables defined inside a function are known as local variables and are known to have a local scope. Local scope is further divided into function scope and block scope but that is not a major concern for us. Local variables can only be accessed from within the function in which they are declared Take this block of code to understand the scope: var siteName = "LinuxHint!";function printSiteName() { let topicName = "JavaScript"; console.log(siteName);} printSiteName(); console.log(topicName); What we are doing in the above code is that we are creating a global variable siteName and we are printing it inside a function called printSiteName(), this function includes a local variable topicName and we are trying to print out the value of this variable outside of this function. Here, siteName is a global variable and topicName is a local variable. The output of the following code is as: As you can clearly see, we were able to access the siteName variables inside a function, but we were not able to access the local variable topicName outside of its function. You can learn more details about these different variables and scope.

 How does a Closure work

Now that we know how scoping works, we can easily understand the working of closures. Closures are functions that are nested inside each other in such a way that the inner function becomes locally scoped for the outer function, and the outer function becomes globally scoped for the inner function. Meaning that the inner function has access to the attributes of the outer function. For better understanding, take the following code: function outerFunction() { let outVar = "I am outer"; function innerFunction() { let inVar = "I am inner"; console.log(outVar); console.log(inVar); } return innerFunction();} outerFunction(); We are creating an outerFunction and an innerFunction inside the outerFunction. From the inside function, we are accessing the variable outVar which is the local variable of the outerFunction, and printing its value along with the value of the variable inside the inner function. This is how this code works: The output of the above code is: We were able to get the values of both the variables and print them out to the console using the console.log() function.

 How to have multiple functions inside another function in a Closure

If we refer to the outer function as the parent function of the closure and the inner function as the child function of the closure. Then we can put it this way that a single parent can have multiple children. A parent function will not have access to the attributes of its children. However, every child will have access to the attributes of its parent. Since, a child function is also an attribute of the parent, so a child function can also access the other child functions of the same parent; this means having access to its siblings. Note: Parameters and arguments are also accessible to children. Suppose that we want to make a function that greets a function that calls it. This function has 3 parameters, firstName, middleName, and lastName. First, create the function using the following lines. function greeter(firstName, middleName, lastName){ // later commands inside here} This greeter function is a parent function with four children. 3 of the children work on the parameters and return the value of the parameters like: function getFirst() { return firstName; } function getMiddle() { return middleName; } function getLast() { return lastName; } The last child, calls all of its siblings and prints the values on the console, which is implemented with the following lines: function namePrinter() { console.log("Welcome! " + getFirst() + " " + getMiddle() + " " + getLast()); } At the end of the parent function greeter() it returns the namePrinter() child to the place where it is called. To, execute this whole Closure we need to call the parent function with the following line: greeter("John", "Bukhari", "Doe"); The complete code snippet of this closure is: function greeter(firstName, middleName, lastName) { function getFirst() { return firstName; } function getMiddle() { return middleName; } function getLast() { return lastName; } function namePrinter() { console.log("Welcome! " + getFirst() + " " + getMiddle() + " " + getLast()); } return namePrinter();} greeter("John", "Bukhari", "Doe"); We will get the following output:

 Conclusion

The closure is a feature that came with the ES6 release of JavaScript. Closures are the implementation of the concept based on the scoping of variables. We learned what closures are and since they are based on scoping of variables we learned about scoping as well. We went through the difference between global scope and variable scope in Js, and in the end, we tested out the working of closures with the help of examples.

JavaScript Array some() method | Explained

Working with arrays is an undeniable part while programming. Array functions are one of the most important features of a programming language. JavaScript comes in many predefined array functions that help us iterate through an array and some even allow us to apply certain conditions on the array. One of these functions is .some() method.

 What is .some() method

To put it simply, the .some() method is used to verify the presence of such an element inside the array that may fulfill a certain condition. To explain it in a little more detail, we can say that the .some() method takes every element from the array, one by one, and compares it against a certain condition given by the programmer. If any of the elements fulfill that condition, the .some() method will stop and return a true value. Otherwise, it’ll return False

 Syntax

array.some(function(value, index, arr), this); The syntax can seem daunting at first, seeing 5 arguments being passed into a function that we thought was pretty simple and easy. Well, we are going to break down and explain each argument. function: A function defined by the programmer invoker against every element in the array (a call back function) value: A non-mandatory argument that explains the value of the current element index: A non-mandatory argument to represent the index of the current element. arr: The whole array itself, a non-mandatory argument. this: Another optional value to be used as the function’s “this” value Return Value: The return value is of the boolean type, it is either true or false Now we know what a .some() method is, what it does, and what its syntax is, but we still need a reason to use this.

 Why use the .some() method

Imagine a problem, you have an array of age values, and you want to know if anyone is above the age of 25. If anyone is above the age of 25 we will call it “valid age”.How to solve this scenario? Well, let’s first have our array containing the ages of 10 people be something like this: age = [12,23,24,11,17,25,26,21,13,24] Let’s try solving this problem using the traditional way, which is to use a loop to iterate through every element of the array “age”: function checkAge(arr){ validAge = false;for (i = 1 ;i 25){ validAge = true; break; }} return validAge;} console.log(checkAge(age)); Now, as you can clearly see in the code snippet above, we first created a function which has a flag variable “validAge” and is given the value False; then we are using a for loop to iterate through every element of the array and comparing it with the age 25. If any of the elements is greater than 25, the value of the variable validAge changes to true, the loop breaks, and the value of validAge is returned. The output of the following code snippet is as: Let’s see how we can accomplish the same task using the .some() method. console.log (age.some(checkAge));function checkAge (age){ return age > 25;} So, let’s go over this very short code snippet. So, we call the .some() method on the array “age” and pass in the function checkAge. The function checkAge takes each element of the array one by one and compares it with 25 and returns true or false based on the condition. The .some() method compares elements one by one by passing it into the checkAge function and upon receiving a true, it stops executing further elements as we have accomplished our task.

 Example 2

Let’s assume that we have an array containing a list of marks of a student in every subject. And we have to find out if that student has failed any subject by scoring less than 40. The array is as: marks = [60,54,85,88,75,39]; We solve the problem with the following code: if (marks.some(compareMarks) == true) { console.log("The student failed a subject or more");}else console.log("The student did not fail any subjects"); function compareMarks (subjectMark){ return subjectMark < 40;} Note: if the marks.some(compareMarks) returns true then we are certain that the student has failed a subject. The output would be:

 Conclusion

The in-built .some() method of JavaScript is really helpful and time-saving when it comes to iterating an array and comparing each element to find if there is any single element in the array that meets a specific requirement. There may be other traditional ways to implement the same task, but they require more lines of code and more processing than the .some() method. We went through what the “.some()” method is, what is the syntax, the return value, and why you should use it in replacement to the traditional methods.

Math.floor(), Math.ceil(), Match.trunc(), and Math.round() methods

JavaScript is one of the well-known programming languages right now, and that is because it has either a package or a library for almost every problem a programmer might face. When developing a JavaScript program or a full-stack web application you have to deal with numbers. In some cases, you do not want a floating number in your variable, that is where the Math Object comes into play. Let’s start by discussing the Math Object very briefly because it is a good practice to understand the basics of something when trying to learn something new.

 The Math Object

Math object is a global object that comes in-built with JavaScript and allows users to perform a variety of mathematical functions when working on a problem that requires such help. What we mean by the term “Global Object” is that you don’t need to create an object of it before using it. However, Math object is not like other global objects, as it is not a constructor. The reason for this is that the Math object and all of the methods inside it are static and that is why we don’t normally call it a “function Object”.

 Math.methods

Math object contains many different methods and we are going to discuss four of them which help us convert any number into an integer: a real number (a number value without the fractional part). The four methods of Math object are: Math.round() Math.ceil() Math.floor() Math.trunc() Syntax The syntax remains the same for all these four methods and that is: Math.method(number \ variable containing number)

 Math.round(x)

This method is quite simple, it takes a number, rounds it off to its nearest real number, and returns that value as an integer. Rounds it off to its nearest number means if the floating-point number after the decimal point is greater than “.50” then the number would round up to the next number. For example, the number “4.57” would round up to “5”. Similarly, if the decimal number after the decimal point is less than or equal to “.50” then the number would round down to the same number e.g. “4.47” would round down to “4”. Let’s take a number whose floating-point number is less than “.50” and store it in a variable like so: const numberValue = 138.2293; Now, let’s pass this value to the Math.round() method and then print it out using console.log() function, just like: console.log(Math.round(numberValue));

 Complete Code Snippet

const numberValue = 138.2293; console.log(Math.round(numberValue)); Output You can witness that the number “138.2293” is rounded down to “138”. Here is another example in which we are feeding a number whose floating point number is greater than “0.50” plus we are directly using a number in the parameters of the Math.round() function. Now, the Math.round() method has rounded up “1.57” to “2” and returned “2” as a result.

 Math.ceil(x)

Math.ceil() method rounds up the number given to it in its parameters. No matter whether the floating point number is greater than or less than “.50”, the Math.ceil() method will simply round up the number given to it e.g. “4.37” would round up to “5” even if the floating point number is “.37”. Let’s take a number and store it in a variable like so: const numberValue = 30.12; Now, let’s pass this value to the Math.ceil() method and then print it out using console.log() function, just like: console.log(Math.ceil(numberValue));

 Complete Code Snippet

const numberValue = 30.12 ; console.log(Math.ceil(numberValue)); Output You can witness that even if the floating point number is as low as “.12” but Math.ceil() method has rounded up the number to “31”. Let’s take another example of Math.ceil() method in which we will feed the number with floating point number “.00” to the math.ceil() function: The output is “922” and you can confirm from this example that the number always gets rounded up using the Math.ceil() method.

 Math.floor(x)

Math.floor() does the exact opposite of the Math.ceil() method, it rounds down the number. For example, let’s take a number whose floating-point number is greater than “.5” and store it in a variable like so: const numberValue = 53.784; Now, lets pass this value to the Math.floor() method and then print it out using console.log() function, just like: console.log(Math.floor(numberValue));

 Code Snippet

const numberValue = 53.784 ; console.log(Math.floor(numberValue)); Output You can see that even if the floating point number is greater than “.5” but Math.floor() method has rounded down the number to “53”. Here is an example of Math.floor() method without using a variable to store the number:

 Math.trunc(x)

This Math.trunc() method returns only the integer part of the number, the part before the decimal point “.”. It doesn’t round off anything. For example, let’s take a number and store it in a variable like so: const numberValue = 434.021395753; Now, let’s pass this value to the Math.trunc() method and then print it out using console.log() function, just like: console.log(Math.trunc(numberValue));

 Complete Code Snippet

const numberValue = 434.021395753 ; console.log(Math.trunc(numberValue)); Output Here is another example without storing the value in a variable: console.log(Math.trunc(874.921395753));

 All four methods together

There is no such constraint that limits us to use only one of these methods on a single number or a single variable. We can use all of these methods on a single variable as well. Just like shown below:

 Code Snippet

Try out these commands in the browser’s console (F12 for chrome) number = 6632.678501;Math.round(number);Math.ceil(number);Math.floor(number);Math.trunc(number); Output

 Conclusion

As a programmer you have to deal with numbers and for that mathematical functions are used. Mathematical functions are exercised on a numerical value to convert them into a real number or an integer., the Global Math object performs various mathematical operations. In this tutorial, we covered four different JavaScript methods to modify the numbers with examples, that are Math.round(), Match.ceil(), Math.floor and Math.trunc().

Prototypes and Inheritance

Inheritance is a concept from object-oriented programming, even though JavaScript fully supports inheritance between parents and children, the working is far from the traditional object-oriented programming, that is because everything is mapped on the primitive constructor Object (Object with a capital O) which is why it is also known as the Master Object. Do not misinterpret this master Object with the datatype Object. JavaScript is often misinterpreted as an Object-oriented language but in reality, that is not true; JavaScript is a prototype-based language. Inheritance is achieved by something called Prototypal Inheritance. To understand that, we first need to be familiar with how a constructor works, how an object is created against a constructor, and what is prototype chaining. This is one of the advanced topics of JavaScript and we are going to take you very slow and try to explain every little bit of information along with snippets, let’s get started.

 How does a Constructor work

Conventionally, constructors are special functions that are executed every time an object is created against a class;, every function expression is a constructor. Now, if you are coming from a trivial programming language and have some background with object-oriented programming, then you are going to get confused. Therefore, try not to compare JavaScript concepts with trivial object-oriented programming. Even though with the arrival of the ES 6 version of JavaScript the keyword “Class” was added into JavaScript, but that is not used to implement the concept of Inheritance., you can create objects mapped on function, yes – functions. Imagine a function created with the following code: var Person = function () {} As mentioned above, that every function expression is a constructor, this can be proved by using the following lines inside the function: var Person = function (name) {this.name = name;this.age = 20} Now, as you can see, we are creating a function and inside the body of the function, we are defining and initializing properties of the object, just like we do in any normal conventional constructor. Now, let’s create some objects mapped to this Person’s constructor function with the following lines of code: var p1 = new Person("John");var p2 = new Person("Albert"); Now, we are creating objects, but we have no method inside objects that will return us the name of the person that we just created, so let’s create that function inside the constructor of the Person object. var Person = function (name) {this.name = name;this.age = 20;this.getName = function(){ return(this.name)} Now, we need to call this function from each individual object using the following lines of code: console.log(p1.getName()); console.log(p2.getName()); After running this whole snippet we get the following output on the console: Now here is the major issue with using this type of template, imagine that you have 100 objects of Person, these 100 Objects will have their own 100 different getName() functions: This is because these objects are the instances of the Person, thus making it redundant on the memory. This is where the Prototype property comes into play.

 The Prototype Property

Every function and every object have a property named Prototype, this prototype contains methods and properties of a function, and this prototype property is shared among all of the instance/objects that are mapped to the function, take a look at this snippet: If we were to create some objects based on this function “x”, they would inherit the methods and properties inside the “prototype” of the function. In our example, the main function would be the Person and the objects are p1, p2, like:

 Using prototype property to create Prototypal Inheritance

Our main issue with the trivial approach was that each and every object had its own getName() functions, the more the objects the more is the number of getName() functions in the memory. To remove this, we write the getName() function outside of the constructor expression and inside the prototype property using the syntax: {objectName}.prototype.{methodName} Our code changes into: var Person = function (name) {this.name = name;this.age = 20;} person.prototype.getName = function() {return this.name;}var p1 = new Person("John");var p2 = new Person("Albert"); console.log(p1.getName()); console.log(p2.getName()); The output is exactly the same as last time: But the difference this time is, that rather than each object having its own getName() function, each object is accessing the getName() function in its parent and using that function to execute the instruction given to it. This is called “Prototypal Inheritance”. Eventually, not making it redundant in the memory.

 Master Object

Everything is essentially an Object, this means that everything is based on Object (with a capital O). To explain this, use the following lines of code and open the console of the browser. var demo = function (){} console.dir(demo); You are creating a function with an empty constructor and the console.dir() displays the details of demo() function definition on the console, you will see this: Expand the little arrowhead, and examine the __proto__ property of this function, the __proto__ property tells us on what object was this function mapped, you will see this: Now, let’s create an instance of this demo function and examine its __proto__ like: var demo = function(){} let x = new demo(); console.dir(x); After running this code, you should see the following output on the console: Expand this and examine the constructor on which the instance “x” was mapped you will see: Meaning that object x has the parent demo, and we already know that the function demois mapped on the JavaScript Object. This creates a prototyping chain as: The object “x” can access the methods and properties of the master object, thus creating a chain of inheritance. If we look in our console for the last time, we can examine that the master Object has this one method in its prototype property which is toString() as: And we call this property on the object “x” and on the function demo that you created as: console.log(x.toString()); console.log(demo.toString()); You get the output as: You can see, both the object and the function were able to access this method even though it was not defined inside them. That is how inheritance works through prototypes.

 Conclusion

Inheritance is very different from our conventional definition of inheritance in object-oriented programming., we achieve inheritance using a property called prototype. You learned how a constructor works, what is the prototype property, how everything inside JavaScript is an Object by learning about Master Object. Moreover, you learned about prototypal inheritance and prototype chaining, and you were able to access the methods and properties of the Master object using the object that you created.

Rest parameter syntax | Explained with Examples

Rest parameters are now becoming an integral part of JavaScript development. Unlike other languages, JavaScript – with the use of rest parameters allows the user to write such functions that can accept any number of arguments and provides the facility to perform actions on those arguments. With the arrival of ES6, a wave of new features hit the JavaScript language, most of these features were entirely new and the others were an efficient alternative to already existing solutions. Rest parameter was one of the new features that got introduced in the ES6 version of JavaScript. By the time you reach the bottom of this page, you would have learned what the rest of the parameters are, how they are different from normal arguments, and how to use them along with their examples.

 Rest Parameters

We have already mentioned what the Rest parameters are, but if we are talking about understanding this new feature then we’ll have to go into a little detail. Rest parameters are defined when we are writing a function just like the normal parameters. But, unlike the normal parameters, to define a rest parameter you need to use a special prefix before the identifier which is a triple dot (…). The arguments that are passed in the parameters are all placed together in an Array. The syntax for defining rest parameter is: function functionIdentifier ( ... argsIdentifier ){ // body of the function} Note: Rest parameters store the arguments passed inside it in an Instance of an array under the same identifier.

 Rules for defining rest parameters

There are certain rules that are to be followed when defining the rest parameter of a function. These rules are really simple and if these are not followed then the program results in an error: There should be only one rest parameter in the function The rest parameter should only be the last parameter of the function Let’s discuss both of them:

 There should be only one rest parameter in the function

A function cannot have multiple rest parameters, because rest parameters are used when you have an unspecified number of arguments. The program cannot differentiate which arguments to put in the first rest parameter and which arguments to put in the second rest parameter. For example, take the following lines of code and try running the program. function linuxHint(...args, ...args2 ){ console.log("Linux Hint Tutorial")} When you try executing the code, you get the following output. The program crashes on function definition and exits the execution with error code 1(unexpected crash)

 The rest parameter should only be the last parameter of the function

Similar to the reasoning of the last rule, a rest parameter can only be the last parameter in the list of parameters of the function because the program will not know when to stop putting arguments inside the rest parameter and to move on to the next parameter. This is because by definition the rest parameter can take an infinite amount of arguments. For example, take the following lines of code: function linuxHint(...args, var1 ){ console.log("Linux Hint Tutorial") console.log(args) console.log(var1)} linuxHint(1,2,2,3,3); When we are calling the function, the program has no idea what our intentions are. Maybe we want to place the first 4 arguments in the args and the last one in the var1; since it is not a syntax error, it is not highlighted by a code editor (in most cases) but when you try compiling the program it crashes on function definition like: The program crashes on function definition and exits the execution with error code 1.

 Fetching Data From Rest Parameters

As we have already mentioned above, the arguments that are passed inside the rest parameters are stored in an array. So, when you want to use the data that has been passed inside the rest parameter you can do that using the way we use to access array data. Let’s first create a function that accepts rest parameters with the following lines of code: function linuxHint(...args) { console.log(args);} We have a function that takes an unspecified amount of arguments and then prints the array that is storing those arguments. To execute this function, we need to call this function with the following line: linuxHint(1, 32, 3, 4, 3, 3, 123, 123, 123, 123); We are passing quite a few arguments during the function call. When you execute the program you will get the following output: From the output, we can clearly conclude that the arguments are being stored inside an array instance.

 How to use rest parameters alongside normal arguments?

We can use rest parameters alongside the normal arguments as well and to explain this we are going to imagine a scenario. A surprise test was conducted in a class and an unknown number of students took that test. The total marks of the test were 50 and any student less than 15 has failed that test. Now, we are going to write a code snippet that is going to take marks obtained by an indefinite number of students and tell us how many students failed that test, but the lower limit of marks (below which the students will be considered to have failed that test) will also be an input which in this case would be 15. So, first, let’s create a function that takes two inputs, one being the lower marks limit and the other would be a rest parameter for marks obtained: function failCounter(passingLimit , ...studentsMarks){ // Later commands inside here} As you can see, we have two arguments: the passingLimit and the studentsMarks (rest param). The next thing we need is a counter variable that will count the number of students that failed the test, and we can create that by using the line: failedStudents = 0; Next up is to go through the array created by the rest parameter and compare each student’s marks with the passing limit. If the obtained marks are lower than the passing limit then we increase the counter variable by 1. Use the following lines of code. for (let i = 0 ; i <studentsMarks.length ; i++){ if (studentsMarks[i] <passingLimit){ failedStudents++; }} The last step would be to display the output with the following lines of code: console.log("Number of Students that took the test: " + studentsMarks.length); console.log("Number of students that failed the test: " + failedStudents); Now that our function is ready to be used, we need to call it and pass in various arguments with the first being the passing limit and the remaining being the marks of the students using the line: failCounter(15,33,23,12,3,5,33,34,23,27,12,3,3,3,11,33,17,19,15,15,23,34,45,45,47,23,19,9); Again, the first argument is the passing limit which we have set to 15. The complete code snippet looks like: function failCounter(passingLimit , ...studentsMarks){ failedStudents = 0; for (let i = 0 ; i <studentsMarks.length ; i++){ if (studentsMarks[i] <passingLimit){ failedStudents++; } } console.log("Number of Students that took the test: "+ studentsMarks.length); console.log("Number of students that failed the test: "+failedStudents);} failCounter(15,33,23,12,3,5,33,34,23,27,12,3,3,3,11,33,17,19,15,15,23,34,45,45,47,23,19,9); When you run the code you get the following output: Our program runs smoothly and without any error, you can try different variations so arguments inside it as well. That’s it for the Rest parameters.

 Conclusion

Rest Parameters are used to accept an unspecified number of arguments inside a function and then being able to perform various operations on those arguments. Other languages usually don’t have this feature, that is why JavaScript takes the upper hand. We took a look at what rest parameters are in detail, how they work, and the rules for defining these rest parameters along with possible errors that can occur if these rules are not followed. Lastly, we learned to use the Rest parameter with an example.

Sorting | Explained

JavaScript comes with a vast amount of methods and functions to complete certain tasks. These methods help when sorting an array. Sorting means arranging a set of values in a specific order, it can be either ascending or descending order. As arrays are an integral part of programming, sorting them is an important and crucial task. There are many trivial algorithms to sort arrays, but why do the hard work when JavaScript comes with predefined sorting methods. We are going to go over sorting an array with string values and numeric values using inbuilt JavaScript functions.

 .sort() Method

The .sort() method is used to sort an array. The order of the sorted array is alphabetically ascending. It works best for String values but produces incorrect results when it comes to numeric values. Now the question comes why the .sort() method does not work for numerical values. To know why the .sort() method works for the strings but not for the numerical values, we first have to understand how the .sort() method works.

 How does the .sort() method work

The .sort() method works by comparing the first character of the string with the first character from the next value. If the characters are the same then it will check the second of both the strings and place the smaller one first. Smaller is decided on the basis of alphabetical order, like in the above example “C” is smaller than “F”. So, when we pass this “.sort()” method two numerical values like “200” and “65”. This function compares the first characters (“2” of “200” and “6” of “65”) and returns “65” as the bigger number. However, in this tutorial, we will also go through an example in which we will sort numbers using .sort() method. Let’s start with discussing and understanding the syntax of the .sort() method. Syntax The syntax of the .sort() method is quite basic. It is: array.sort() Return Value: A sorted array. For example, let’s take an array with different items inside it: array = ["Table", "Chair", "Glass", "Mouse", "Laptop", "Fan", “Car” ]; To sort this and display the output we are going to use the .sort() method inside the console.log() method, like so: console.log(array.sort()); The complete code snippet would become: array = ["Table", "Chair", "Glass", "Mouse", "Laptop", "Fan", "Car"]; console.log(array.sort()); Run the program to observe the output:

 .reverse() function

The .reverse() function doesn’t sort an array in any order. However, it reverses the positioning of elements inside the array. Meaning the last element of an array becomes the first element. The syntax is as: array.reverse() If we take the array from the above example and try reversing it using the .reverse() method then the code snippet would be something like this. array = ["Table", "Chair", "Glass", "Mouse", "Laptop", "Fan", "Car"]; console.log(array.reverse()); The output is as: As you can see, the elements of an array are now in reverse order. But how do we actually sort an array in descending order?

 How to sort array values in descending order?

Well, we have to use a combination of the .sort() and the .reverse() method. We first sort an array and then we use the .reverse() method to sort the array in descending order. This sounds a little confusing, so let’s try to observe an example. For this example, take the array from the above examples. array = ["Table", "Chair", "Glass", "Mouse", "Laptop", "Fan", "Car"]; Now that we have an array in completely random order. The first step is to sort it, so let’s do that: using array.sort() Now that the array is sorted, we need to reverse it using the following line: array.reverse(); The last step is to observe the output, and to do that we are going to display the array using the console.log() method like this: console.log(array); The complete code snippet is as array = ["Table", "Chair", "Glass", "Mouse", "Laptop", "Fan", "Car"]; array.sort(); array.reverse(); console.log(array); The output is as: That is it, that is our array sorted in descending alphabetical order. Now let’s see how to work with numeric values.

 How to sort Numeric Values using .sort() method

As we have already mentioned above, the .sort() method does not produce correct results when it comes to sorting numeric values, and that is because the .sort() method works by comparing strings, it considers numeric values to be strings and then compares them. Let’s start off by creating an array of numeric values. Like so. numberArray = [2,3,4,6,66,100,25,33] Now, let’s observe the output by running the. sort() method on this array inside the console.log() function console.log(numberArray.sort()); The output is as: As you can see, the outcome is off the mark. Why is that so?. Well, we have already explained how the .sort() method works. What happens is that it takes the first character of the string and compares it with the first characters of the next value, although 100 is bigger than 33. But, when you compare the first characters, “1” is smaller than “3”, hence 100 is placed before 33. So do we fix this issue? Well, we do that by using a compare function inside the sort function. The compare function is as: function(a , b) {return a-b} We take the “numberArray” from the above example and apply this compare function on it to observe the output. numberArray = [2, 3, 4, 6, 66, 100, 25, 33]; numberArray.sort(function (a, b) { return a - b;}); console.log(numberArray); With this, we get the following output. As you can see, we finally have our number array sorted in descending order.

 How to sort numeric values in descending order?

Now that we are familiar with sorting a numeric array in ascending order, we can start trying to sort it in descending order. Just like trying to sort strings in descending order, we can use the reverse() method to reverse the numeric sorted array like so: numberArray = [2, 3, 4, 6, 66, 100, 25, 33]; numberArray.sort(function (x, y) { return x - y;}); numberArray.reverse(); console.log(numberArray); The output is as: However, there is another way of doing that, and that is to change the return statement in the compare function. Change the statement to this: return b-a; After that, we simply print out the array using the console.log() method. The complete code snippet is as: numberArray = [2, 3, 4, 6, 66, 100, 25, 33]; numberArray.sort(function (x, y) { return y - x;}); console.log(numberArray); The output will be:

 How to sort object arrays

Imagine we have an array of objects, For example, let’s take objects of people with their name and their year of birth. Now we want to sort this array by the year they were born. We have the people’s object array as: const people = [ {name:"Albert", yob:1997}, {name:"Dave", yob:2005}, {name:"John", yob:2000}]; Now we can sort this object array using .sort() and compare function as: people.sort(function (x, y) { return x.yob - x.yob;}); Now the last thing is to display this array using the following code: console.log("The people in age-order are as");for (let i = 0; i <= people.length; i++) { console.log(people[i].name + " is born in " + people[i].yob);} The complete code snippet is as: const people = [ { name: "Albert", yob: 1997 }, { name: "Dave", yob: 2005 }, { name: "John", yob: 2000 },]; people.sort( function (x, y) { return x.yob - y.yob;}); console.log("The people in age-order are as");for (let i = 0; i <= people.length; i++) { console.log(people[i].name + " is born in " + people[i].yob);} When we run the file we get the following output: As we can see, all the objects are now sorted based on their “yob” which is the year of birth of the person. That is it for sorting.

 Conclusion

Sorting is an essential part when working with arrays. JavaScript comes with various inbuilt functions that help us in sorting array elements. We learned how the .sort() method works, its syntax, and its return value. Moreover, we learned how to use the combination of .sort() and .reverse() method to sort arrays in descending order. Lastly, we learned how we can use the .sort() method for sorting numeric values using the compare function.

Top 5 JavaScript Playgrounds

Code playgrounds are online code editors that are available publicly. They are more like services that allow you to create, edit, share, fork a snippet of code, and much more. Nowadays, code playgrounds are available for almost every language that is available in the market. Just to put it into perspective, there are code playgrounds available for GW-Basic (which if you don’t know is the most basic of programming language and is also outdated) and there is also a playground available for training your very own Artificial Intelligent bot through Python (along with the capability of loading, and creating datasets).

 Who should use Code Playgrounds?

Are you new to programming in general, or are you familiar with the concepts of programming? You are moving towards new technology or you want to try out a block of code before you put it in your project. Well, in such scenarios, the code playgrounds are the best services available for you. New programmers might want to get some sort of motivation by trying out some basic lines of code. Note: The above code is from Google’s Colab code-playground. But, what if you are an expert in something? Well, even then code playgrounds are useful to you. You can keep up with coding trends on these code playgrounds. And, if you want to show off your skills to your friends, then some of these online coding platforms allow the feature to do exactly that. Now that we have a basic understanding of what code playgrounds are, We can now talk about the topic at hand, that is, Best JavaScript Code Playgrounds, available on the internet.

 Top 5 JavaScript Playgrounds

The list goes as: CodeSandbox.io JSFiddle Codepen.io StackBlitz Sololearn Let’s go over all of them one by one. 1. CodeAndSandbox.io Let’s just create this scenario that you want to create static websites or a full-stack web app. Let me emphasize it a little more, if you want to create a FULL STACK WEB APP using only a web browser, then CodeSandbox.io is the right playground for you. CodeSandbox.io works on the concept of sandboxes. If you don’t have the concept of sandboxes then in simple words, it is an isolated testing environment. CodeSandbox.io’s sandbox is a no-setup environment that is made for super-fast development purposes. Sandboxes, in general, are mostly used for testing purposes. CodeSandbox.io includes support for JavaScript and almost all of its popular frameworks, and CodeSandbox is one of the very few playgrounds that support Backend development along with the traditional front-end development. Moreover, there are templates available for all these frameworks. So, you just have to go to their website and choose from the template available to start coding. A snippet of the CodeSandbox.io coding page shows a lot of JavaScript frameworks as: Key Features Git integration Support for back-end along with front-end development Can be used to develop a full-stack web app Templates available for major Js Frameworks Auto-configuration Support for VS code integration (Visual Studio Code) Host Static websites Note: One major benefit of using CodeSandbox.io is that you don’t have to worry about setting up the configuration as CodeSandbox takes care of it. 2. Codepen.io If you are only interested in front-end development and want to try something out, or maybe build a project to show off your skills in front-end development, then chances are you have already heard the name CodePen.io. Well, CodePen.io comes in with the support to share your projects with the world, with git integration, and allows the user to use external javascript libraries. Another feature that is available in CodePen.io is that it provides the user with error analysis and a fully working terminal. Key Features Git integration \ support Allows users to share projects with other users Setting up is effortless Big community to share the projects with Stay up-to-date with front-end trends Helps in sharing code snippets 3. StackBlitz If you are like most of the programmers out there that love the Visual Studio Code, then chances are that you are going to like this next sandbox a lot. Stackblitz is an online javascript playground that is powered by Visual studio code: Stackblitz is one of the most popularly known JavaScript playgrounds out there because of being very similar to visual studio code. Stackblitz comes with the ability to create a development-ready environment with a single click. It comes with the support to develop full-stack web applications as well, with an info panel to run Angular and React CLI commands in, meaning there is no explicit terminal to run these commands in. Key Features It is powered by Visual Studio Code Supports Backend development as well as Frontend One-click setup. Offline Development (because of the in-browser development environment) TypeScript support (because of VS code support) Visual Studio Code integration Git support Sharing project using an invitational URL link 4. JSFiddle JsFiddle is one of the earlier JS code playgrounds. JsFiddle puts more emphasis on coding and development, that is exactly why, when you visit JsFiddle’s website you are greeted with a 4 terminal layout, HTML, CSS, JavaScript, and a result’s terminal. JsFiddle is a unique javascript playground, having unusual support for asynchronous ajax requests, which is highly unlikely in even the newer JS code playgrounds. On JsFiddle, the code snippets or static websites are known as “Fiddles”, and the user can share the code on Stack Overflow. It even contains a bug static report for git. Key features Asynchronous Ajax request support Sharing fiddles on Stack Overflow Bug Statistic Report Start coding instantly Support for installing external JavaScript frameworks Git integration 5. SoloLearn SoloLearn is a famous online learning platform for new and average coders. They have their course focusing on web development. It is an immensely popular learning platform and has millions of solo learners registered on their platform. Apart from that, SoloLearn has its code playground. It may not be that much unique when compared with other JavaScript Code playgrounds available on the internet, but it is unique in its own ways, especially, the SoloLearn platform has a vast global community that keeps the user up-to-date with the changes in coding trends and practices. When you visit SoloLearnCode, which is their code playground, you are greeted with a dialogue box that asks you about the language\technology that you want to test out. As you can see, SoloLearnCode isn’t only a JavaScript code playground but it supports a variety of programming languages. Anyways, after selecting the template or the technology that you want to work with, you are taken to its IDE, which is rather simple unlike other code playgrounds; it provides a clean and distraction-free environment. Key Features Massive Global Community Support for console Supports multiple languages Live Sharing Bug Report

 Conclusion

There are hundreds of JavaScript code playgrounds available, but no one wants to work with something mediocre. In this write-up, we went through the Top 5 JavaScript Playgrounds, learned about their features, and even learned about their uniqueness when compared to other code playgrounds that are available on the internet. But, in the end, it all comes down to your personal preference and your requirements. So, feel free to give them all a try, and decide which one is “The One” for you.

JavaScript Array join() method | Explained

JavaScript is a high-level web programming language that lets a developer build complex web applications and web pages by giving the ability of interactivity to the web pages. Like any other programming language, JavaScript arrays come with built-in methods that are set or collections of statements already defined. One of the built-in methods is the join() method. In this post, we will go through the JavaScript join() method along with examples to better explain the concept.

 What is the Array join() method?

The array join() method is an inbuilt method introduced with the ES1 feature in 1997 whose function is to add all the elements in an array and return a string with a separator separating all the elements.

 Syntax of join() method

The syntax of the array join method is given below: myArray.join(separator); The separator argument is optional and if you do not specify a separator then the join() method will return the string with a comma separating all the elements. It should be noted that if the array is empty, null, or undefined the join() method will return an empty string. Also, if the array has only one element then the join() method will return that element as a string without the separator. Now that we know what an array join() method is, let us go through some examples to better explain this concept. Example 1 In this example, we will simply go through the join method by first initializing an array containing bird names and then applying the built-in method of join() on this array. // array containing bird namesconst birds = ['Eagle', 'Dove', 'Parrot']; console.log(birds.join()); // Eagle,Dove,Parrot At the end, we put the console log so whatever string will return from the join() method will be displayed on the console log: Example 2 This example is the same as example 1 except that in this example we will pass a separator “-” in the join() method: // array containing bird namesconst birds = ['Eagle', 'Dove', 'Parrot']; console.log(birds.join('-')); // Eagle-Dove-Parrot We will now see that the elements are separated with a dash: Example 3 If you don’t want any separator then you can simply pass a blank string in place of the separator as shown below: // array containing bird namesconst birds = ['Eagle', 'Dove', 'Parrot']; console.log(birds.join('')); // EagleDoveParrot

 Conclusion

JavaScript offers arrays that have some in-built methods like the join() method. The join() method takes a separator as an argument which is optional and returns a string joining all the elements of the array. If you don’t specify a separator then the join() method will return a string separating the elements with a comma. In this post, we explored the JavaScript Array join() method, and to grasp this concept we described three examples.

How to Write Your First JavaScript Program

JavaScript has been in the market for over two decades now and it is leading the current computer market by a huge margin. In the previous few years, JavaScript has become immensely popular, and programming is essential if you want to work in web development.

 Why JavaScript?

Whenever someone thinks about learning programming, the biggest question that one must answer for himself is “Where to start from?”. Well, starting with JavaScript seems like the best option available right now because it is easy to understand, there are tons of tutorials available on the internet and it spreads to major fields such as Web-development, Mobile Development, Server-side development, and so on. Just to mention JavaScript was the most popular language of the year 2020 according to Stack Overflow Developer Survey 2020, here is the survey result: Now that we have established that we should start learning JavaScript, we are greeted with another question which is “HOW to get started with JavaScript?”. There are some prerequisites for learning to program such as: A compatible browser (Almost all browsers Support Js) An Internet Connection A Code Editor (most famous being Visual Studio Code) A strong will to learn

 Writing Your First Program

It is generally a good idea to test out something before properly investing yourself in a field. You can do that pretty easily when it comes to trying out JavaScript. For this tutorial, we’ll be using the browser’s in-built console to test out JavaScript. Firstly, open up the browser’s console. You can do that by pressing F12 for chrome and Ctrl + Shift + K for firefox. You should see something like this: Almost every current day browser supports JavaScript, that is why we can start JavaScript code directly inside the terminal or console. Type in the following command inside the console and press enter. console.log("hello LinuxHint"); After pressing the enter key, you should see something like this on your screen: The first line is the JavaScript command that you wrote, and the follow-up line is the output of that line. And with that, you have created a simple, traditional “Hello” program. But let’s try to create something a bit interesting. Let’s try to show an alert box on the browser to greet the user with the following code: alert("Hey! Welcome to our Page"); When you press enter, you would see a pop-up on the top of the screen with the alert message like: That’s it, you have successfully learned how to run your first JavaScript program. But, there is still one unanswered question remaining that is crucial to progress as a JavaScript programmer and that would be “how to learn JavaScript?”

 How to learn JavaScript efficiently

There are no shortcuts to learning JavaScript or any programming language for that matter, all you need is practice. But learning JavaScript is all about finding the right tutorials and the right documentation. Becoming a top-tier JavaScript programmer is rather easy. As we have already mentioned, due to JavaScript’s popularity, there are gazillions of tutorials available on the internet. However, the best practice is to go over the official documentation by the MDN which stands for Mozilla Developer Network. Moreover, to find answers to various emerging questions, to know about different and intriguing features of JavaScript and its various frameworks, you can visit Linuxhint’s JavaScript Category.

 Conclusion

To learn JavaScript, you need to start from the very first step as there are no shortcuts available to learning any programming language. We learned how to run your first JavaScript program through the browser console and how to make it more interactive by using the alert feature. We even answered two major questions: Why JavaScript? and how to learn JavaScript efficiently. We hope that with sufficient practice you’ll be able to become a JavaScript expert and develop top-tier applications.

How To Work with JSON?

JSON stands for JavaScript-Object-Notation and it is the most widely used structured data type for transferring data across the internet. JSON is based on JavaScript objects but it is language-independent; which means that it can be used in almost every modern-day programming language.

 JSON -Basic Intro

JSON is the textual representation of data that makes it easy to transfer data at really high speeds. In JSON, you differentiate a key and value by putting a colon “:” in between them, and you put a comma in between different key-value pairs. Moreover, the key = value pairs are enclosed inside curly brackets:

 Syntax of JSON

The syntax of JSON is pretty simple, it is as follows: { key1: value, key2: value}

 Working with JSON

To work with JSON, the JSON is first stored inside a variable to make it a JSON object. For example, imagine that you have a JSON data of a person containing the following information like: { firstName: "John", lastName: "Doe", age: 22, city: "Newyork",} To convert it into a usable object, we simply put it equal to an object with the following code: const person = { firstName: "John", lastName: "Doe", Age: 22, City: "Newyork",}; As you can see, you created a variable person that now holds an object with the information about that person like firstName, lastName, and so on; To make sure we are able to use it inside JavaScript we are going to simply print this object to the screen using the console.log() function: console.log(person); The complete code Snippet would be: const person = { firstName: "John", lastName: "Doe", Age: 22, City: "Newyork",}; console.log(person); When you run this code, you will see the following output: As you can see on your console, we can see an object being printed. This is because we created an object by setting it equal to a variable.

 Accessing Value from a JSON object

To access the values from inside the JSON object, you use the dot-operator with the name of the “key”. Taking the above JSON object, if you want to print out the first name, use the following line: console.log(person.firstName); You will see the following output: You can even print the full Name using the following line: console.log( "The person's full name is as: " + person.firstName + person.lastName); You will get the following output: As you can see, we concatenated the first name and the last name and displayed it on the console. This way you can access JSON key-value pairs.

 Appending in JSON object

If you want to append a value inside a JSON object, you can do that by using the dot-operator. First, give the “key” after the dot and set it equal to its value as shown in the following syntax: jsonObject.newkey = value; In case you want to add the job of the person in the object mentioned in the above example then you can do that by using the following line of code: person.job = "Auditor"; console.log(person.job); The complete snippet is as: const person = { firstName: "John", lastName: " Doe", Age: 22, City: "Newyork",}; console.log( "The person's full name is as: " + person.firstName + person.lastName); person.job = "Auditor"; console.log("And the person's job is: "); console.log(person.job); When you run the above code snippet you get the following output on your screen: As you can see, the job was not part of the JSON object at first, but you were able to append it into the JSON object and print it out to the console as well.

 Converting JSON object into String Object

As mentioned above, JSON is transferred as textual data, so if you want to convert a JSON object into a string object you can do that by using the method: JSON.stringify( object ); If you want to convert the above-mentioned person object into a string and print it on the console, you can do that using the following lines of code: console.log(JSON.stringify(person)); When you run the code, you will get the following output on your screen: As you can see, the JSON object has been converted into a String object, this is highly beneficial in transferring data across the internet at really high speeds.

 Conclusion

JSON is the world’s most widely used data transferring structure because of being really light-sized and easy to transfer. JSON is based on the syntax of a normal JS object, but it is totally different from the JS Object as an object can have a method inside it while JSON is only information as it contains key-value pairs. However, it is not confined to JavaScript, JSON is available in almost every programming language. We learned about JSON, its usage, how to work with JSON within JavaScript, how to access JSON values, and how to append into a JSON object. Lastly, we learned how to convert a JSON object into a string object.

How to work with Date and Time | Explained with Examples

Oftentimes when you are developing a program, you need to ask the users about their date of birth or date of joining or to save the date at the time of input. The bottom line is, you need to work with “date and time” while developing programming independent of the programming language, meaning that you have to know date manipulation in programming., you can also work with date and time by using the Date object which is inbuilt in JS.

 What is the Date Object?

As the identifier is pretty self-explanatory, the Date object is one of the many objects that come in default with JavaScript. The date object displays date output as a String by requesting the current time zone of the browser on which the JavaScript is being executed. If you are running JavaScript on a code editor something like a Visual Studio Code, then the JavaScript will access the machine’s clock to get the current time and date.

 How to use the Date Object?

Even though the Date object is a built-in object, to use this, you need to create its object using the “new” keyword. So, before using the Date object we need to initialize an object with the following command: variable = new Date(arguments); Note: Arguments in the Date object’s constructor are optional. You can create a new Date object using one of four methods which are going to be discussed next.

 Creating a Date Object using timestamps (ms)

You can create a Date object using timestamps and these timestamps are given in milliseconds. Remember, the milliseconds are counter after the epoch time., epoch time is 1st January 1970. For example, try out the following command: var date = new Date(15522354652); console.log(date); We are creating a new object and passing the timestamp in milliseconds. When we are logging “date” variable in console, we get the following output: As you can see, we were able to create an object using milliseconds (timestamps) in the arguments.

 Creating a Date object (current time)

If you want to create a Date object that has recorded the current time, the time of its creation, then you can do that by not passing any argument to the constructor. You can do that by using the following lines of code: var date = new Date(); console.log(date); As you can see in the code, we are not passing any argument to the Date constructor. When there are no arguments in the calling function, then the Date object stores the current time from the browser’s time zone or by accessing the computer’s clock. As you can see, we were able to create an object to store the current time and date, and then we used the console.log() function to print out that date and time.

 Creating a Date object using specific arguments

You can create a date object by using a specific date and passing them in different arguments. The syntax for creating such an object is as: new Date (year, month, day, hour, minute, second, milli-second) Let’s try making a date object with the time being 08:54, 5th of June 1997. To do that, we use the following lines of codes: var date = new Date (1997,5,5,08,54); console.log(date); As you can see, in the month’s parameter, we want to give ”June” which is the 6th month but we are passing the value 5. Well, that is because the count for months starts with 0’s Date object with 0 being January and 1 being February, and so on. Since we are not giving arguments to the second and millisecond parameters, their default value is being selected. The output of the following code is: We successfully created an object using the date-specified arguments.

 Creating a Date object using Date String

We can also pass in a Date string inside the argument of the Date constructor. Just like the last example, let’s try creating a date object on 5th June 1997 by using the following lines of code: var date = new Date("5 June 1997"); console.log(date); The output of the following lines of code is: We created an object using a Date-string based argument. We can use the following table to put all the different constructor syntax in one place
SyntaxPurpose
new Date(); To create an object with the current date and time
new Date (timestamp in milliseconds )To create an object with a date that is a certain millisecond from 1 Jan 1970.
new Date (year,month,date,hour,minutes,seconds,ms)To create an object with a specific date and time using specified arguments
new Date (“Date String”)To create an object with a specific date and time using the Date-string argument.
So far, we have learned how to create an object using various constructors of the Date object. We still have to get this date from the object.

 Fetching Date from the Date Object

There are various methods that allow us to fetch a certain attribute of the Date object. Sometimes you want to return a specific value of the Date-time object, like the month or only the year. To fulfill this purpose there are various .get() methods. These methods are: date.getTime(); \\ Milliseconds since epoch date.getMinutes(); \\ Minutes of the hour date.getYear(); \\ Only the year date.getSeconds(); \\ Seconds of the minute date.getDay(); \\ Only the day date.getFullYear() \\ Year in 4-Digits There are many more get methods available like: Let’s create a date object using the current date and time and then fetch minutes and only the year. Using the following lines of code: var dateValue = new Date(); console.log("The minutes in the hour are: " + dateValue.getMinutes()); console.log("The Year in four digits is : " +dateValue.getFullYear()); The output is: That’s it now we know how to manipulate Date and time using JavaScript.

 Conclusion

We can work with Date and Time by using one of the built-in objects named the Date object. Unlike the other default objects of JavaScript, we need to first create an object with the “new” keyword to utilize the functionalities of this Date object. We learned how to manipulate date and time with the Date object by using its various constructors along with their examples and learned how to fetch data from this object.

How To Use the JavaScript Developer Console?

Sometimes when you are starting out with JavaScript, it’s better to run some JavaScript code inside the developer console, because you don’t want to jump into the development through a code editor right away. Maybe you aren’t starting out, but you come across a fascinating JavaScript method that you want to test out. As a JavaScript developer, the quickest way to run a code snippet is using the developer console of the browser. These consoles are designed to help web applications developers as they don’t need to make a separate HTML file to test a simple JavaScript method. Almost every modern web browser comes with the support of running the JavaScript commands from its developer console. This feature is highly used because of the fact that it doesn’t only save time but you don’t require much processing power to check out some basic functionalities of JavaScript. We are going to learn how you can navigate to the developer’s console for different browsers and then try out some JavaScript commands inside them.

 Microsoft Edge’s Developer Console

You can access the developer’s console in Edge using the following steps: Click on the options button After clicking the options button, you’ll see a drop-down list of various options; hover the option that says “More tools” From the list, click on “Developer tools” After that, the developer console will pop up on the screen Shortcut Key: Ctrl + Shift + I

 Opera’s Developer Console

To open up the developer console in the opera web browser do the following steps Click on the opera’s “O” icon in the upper left-hand corner From the drop-down menu, hover on the option that says “Developer” From the pop-up list click on the option that says “Developer tools” The developer console will open up in front of you, like this Shortcut Key: F12

 Mozilla FireFox’s Developer Console

To open firefox’s developer console, follow these steps Click on the hamburger sign “ ” as shown on the gif below From the drop-down menu, select “More tools” From the new list, click on the option that says “Web Developer tools” You‘ll have the developer console in front of you just like this Shortcut key: Ctrl + Shift + K || Command + Option + K

 Google Chrome’s Developer Console

Access Chrome’s Developer Console by: Click on the 3 dots also known as the options button as shown in the gif below From the drop-down menu click on “More tools” From the new pop-up list click on “Developer tools” The console will open up like this Shortcuts Key: Command + Option + J || Control + Shift + J

 Trying out JavaScript commands in Developer Console

Let’s test out by running JavaScript commands in the Developer console, for this tutorial, we’ll be using Google Chrome’s developer console. Let’s print out “Hello World” using the command: console.log("HELLO WORLD! This is LinuxHint!"); The output is as: But printing out “Hello World” is rather boring, let’s try to use the browser’s alert dialogue box to say hello to the world. You can do this by using the “alert” command: alert("Hello World! This is LinuxHint"); Type or copy this command in the console and press enter. You’ll see an alert box like this: That’s it, now you know how to run JavaScript in the Developer console in various browsers.

 Conclusion

Developer Console provides the facility to run JavaScript code directly inside the browser without having the need to deploy an HTML web page along with its script page. We learned how we can navigate to different browser’s developer console pages. We tested running the JavaScript command in the console and we prompted the user using the browser’s in-built alert dialogue box. We hope you can utilize the facility of running JavaScript straight in the browser’s console and learn more about JavaScript.

How to Search Through Arrays using Array methods?

When working with programming languages, you would often find yourself working with various kinds of data placed inside Array variables. JavaScript is no different when it comes to utilizing data in arrays. The trivial way of searching data inside the arrays is by using some kind of loop, most preferably the for loop. However,, there are various methods that ease out the process of searching through an array. We are going to look over some methods that help us search for an element inside an array. These methods are: includes() indexOf() find() filter() To test out all the methods in this tutorial, we are going to create an array containing various elements: array = ["Google", 13, 66, "This is a long sentence", "Table and Chair"];

 The .includes() method

When you want to go through an array just to answer the question “Does this element exist in this array or not?” you use the .includes() method. The way the .includes() method works is that it searches every element inside the array for a match and if it finds any match it returns true otherwise it will return false. Syntax of .includes() method arr.includes( elem ) ; Return Value: A boolean value Example Now that we have our array: array = ["Google", 13, 66, "This is a long sentence", "Table and Chair"]; Let’s try to find if there is an element “Google” present in it, by using the following line of code: console.log(array.includes("Google")); The output is: It returns true, meaning that the element we were searching for is indeed present in the array. Time to check if the number 23 is present inside our array or not. We can search for 23 by using the command: console.log(arr.includes(23)); We get the output: It returned false, meaning there is no such element present inside the array.

 The .indexOf() method

The indexOf() method works in a similar way to the includes() method but a subtle difference between these two functions is that the indexOf() method searches the array for the desired element and returns its index value instead of returning only a boolean value. If there is no such element present inside the array then it returns the index value of -1. Syntax of .indexOf() method The syntax of the .indexOf() method is quite basic. It is: arr.indexOf( elem ) ; Return Value: Index of the element inside the array. Example Taking the array declared: array = ["Google", 13, 66, "This is a long sentence", "Table and Chair"]; We are going to test out this function by trying to find the element “Table and Chair” with the following command: console.log(array.indexOf("Table and Chair")); The output is: The output is 4, as the element “Table and Chair” was the fifth element inside the array and we know that the first element inside the array starts from index “0”, so that is why the 5th element has the index 4. Let’s take another example in which we will try to find the index of the element “Yahoo” inside our array. console.log(array.indexOf("Yahoo")); We get the following output: As we can see the output is -1, which means the element “Yahoo” is not present inside our array.

 The .find() method

The .find() method takes in a callback function and iterates over the whole array in order to find and return the first element which fulfills a certain condition given in the callback function. Syntax of .find() method The syntax of .find() function is: array.find( function ( element [,index[, array]] this.arg ) ; This method has quite a few parameters: function: the callback function that will be checked against every element of the array. this: default parameter – this argument of the method The callback function further takes three arguments: element: the single element of the array during iteration, that is being matched against a given condition in the function index: Current element’s index array: of the current element Return Value: The element that passes the condition otherwise undefined. Example Let us try to find an element inside the array that has a length of more than 10 using the following command: console.log (array.find (elem => elem.length > 10) ) ; We get the following output: The first element that has a length more than 10 was printed even though there was still another element inside the array who had a length of more than 10. Let’s do this one thing, changing the condition from more than 10 to more than 30, we know we don’t have any element inside our array that has a length of more than 30. Use the following command: console.log(array.find(elem => elem.length > 30)); The output we get is: As we already knew, we had no element with a length more than 30, therefore, the function returned to us with “undefined”.

 The .filter() method

As we are aware now that the .find() method only finds the first element that fulfills a certain condition and then stops executing. But most of the time, you don’t want that, you want a list of all the elements that fulfill that specific condition. That is why we use the .filter() method. The .filter() method searches the array for and returns an array of all the elements that fulfill a certain condition. Syntax of filter() method The syntax of the filter() method is quite similar to the .find() method. It is as: array.find( function ( element [,index[, array]] this.arg ) ; Let’s explain its parameters very briefly. function: the callback function this: default parameter – this argument of the method The callback function further takes three arguments: element: the single element of the array during iteration, that is being matched against a given condition in the function index: Current element’s index array: Current element’s array Return Value: An array containing all the elements that passed the condition, otherwise an empty array. Example Let’s take the example from the previous method, which is, to check the array for the elements that have a length of more than 10 by using the command: console.log(array.filter((elem) => elem.length > 10)); The output of the command is as: As you can see, this method returned an array of all the elements that fulfilled our condition. But what if, just like the examples in the previous method, we want to search for the elements with a length of more than 30?. Well, we do that by using the following statement: console.log(array.filter((elem) => elem.length > 30)); The output we get is: Since there was not even a single element inside the array that had a length of more than 30, that is why this method returned us an empty array. So, in the end, we are now aware of some answers after using these methods: Do you want to know if an element is present inside an array? Use the .includes() method Do you want to find and get the index of a specific element inside the array? Use the .indexOf() method Do you want to know which element or elements meet a specific condition? Use the .find() and .filter() methods

 Conclusion

Dealing with data that is stored inside arrays is a crucial and integral part of any programming language especially when you are working with structured data inside arrays. We can search through an array using the four key methods provided within JavaScript. These methods are namely includes(), find(), indexOf(), filter(). We learned the syntax of these methods, their return values along with their examples.

How to replace all substrings in a string using the replace() method?

String operations are one of the most important features of a programming language. Nowadays, authorizing passwords to confirm valid email addresses, verifying the format of a postal address, and verifying the number of digits in a phone number is done with the help of string operations. There are numerous string operation methods available, each with its own usage benefits and its determinants. One of such methods is the .replace() method.

 What is the replace() method?

As the name indicated, the .replace() replaces a string or a part of a string(substring) with another string. The syntax of the .replace() method is quite simple: string.replace(valueToSearchFor, valueToReplaceWith); There is a unique factor about the .replace() method, and it’s present in its syntax. So, let’s explain the syntax. string: The string whose substring is to be changed. valueToSearhFor: A substring or a regex to match the “string” against. valueToReplaceWith: New substring that will replace the old one. Return Value: A string with the modified substring. Example A simple example of the .replace() method would be as: string = "Hello World, Welcome To LinuxHint"; console.log(string); newString = string.replace("World","Programmers"); console.log(newString); What we are doing here is that we are creating a variable “string” and giving it some textual value which is “Hello World, Welcome To LinuxHint”. We want to replace the substring “World” with “Programmers”, that is why we have created a new variable and named it “newString” and passed the value returned from the .replace() method. Finally, we have the console.log() to print out the values of both variables. Output As we can see, the variable “newString” has the updated string inside it.

 How to use regex in .replace() method

What if we want to search for multiple instances of the same string? What if our string is like this: string = " Brown mat, Brown Table, Brown Chair, Brown Mug"; And we want to replace all the “Brown” substrings with “Blue”. Let’s give it a try using the method that we have learned above. string = " Brown mat, Brown Table, Brown Chair, Brown Mug"; newString = string.replace("Brown","Blue"); console.log(newString); The output is: The output is: That is not what we wanted. So what went wrong? Well, Nothing went wrong. The way the .replace() method works is that it finds the first instance of the substring, replaces it, and stops executing. So, if we want to check for multiple instances we have to use regex with the global flag “g”. Learn more about regex. Now, we are going to use regex in the first argument of the replace() method instead of a normal substring, like: string = " Brown mat, Brown Table, Brown Chair, Brown Mug" ; newString = string.replace(/Brown/g,"Blue"); console.log(newString); As you can see in the below-given image, we have replaced the first argument from a substring to a regular expression with the global flag “g”. The output now is: We got exactly what we wanted. But there is still something missing, and that is the case where the multiple instances of the same substring are different case-sensitive. Imagine the same string from above but with slight changes like this: string = " Brown mat, brown Table, brown Chair, Brown Mug"; Now, as you can see, the substring that we want to replace “Brown” has two different case-sensitive versions, one starting with the capital letter “B” and the other one starting with the lower letter “b”. If we use the normal regex with the global flag “g” like so: string = " Brown mat, brown Table, brown Chair, Brown Mug"; newString = string.replace(/Brown/g, "Blue"); console.log(newString); We get the following output: We are going over multiple instances but our search method is case-sensitive. To change it to case-insensitive we can use the flag “i” along with the global flag “g” like: newString = string.replace(/Brown/gi, "Blue"); When we are using this statement instead of the old one we get the following output;

 Conclusion

In JavaScript, we can replace a substring from a string value by using the .replace() method. The .replace() method takes two arguments, the first being the substring or a regular expression and the second one being the substring that will replace the old substrings. We have learned what is the syntax of the .replace() method and what is its return type. Moreover, we used the .replace() method in different examples using both the substring and regular expressions to search for possible matches in a string and we even went through different flags when using regular expressions.

Modules, Import, and Export Statements | Explained with Examples

Modules are used to implement the concept of modularity which is, at its very core, the process of dividing a solution into smaller, compact, and more meaningful components., modularity is achieved by using exports and imports keywords. When JavaScript is used as a modular script with an HTML webpage, the keyword “module” is added as the type of the script tag

 Why use Modules

Avoid repeating the words. “With the passage of time web applications changed from being very small programs to big and complex programs to accomplish complicated tasks. To make bigger/complex web applications, ES6 JavaScript came with the capability to divide scripts into smaller and manageable components with the use of the export feature and the import feature.

 Setting up an HTML page

Go into your preferred text editor and create an HTML page, simply put the following lines of code inside the body tag: <center> <div id="demo" style="background-color: cadetblue"> <p>JS Modules Explained</p> </div></center> Instead of manipulating the HTML elements on a web page, we are going to display and verify output using the console. Therefore, we do not require fancy elements on our HTML webpage. Run the file and you will see the following output:

 Setting up Script Files

Now, while staying in the same directory where your HTML file is, create two “.js” files as: mainScript.js: This file will be linked to the HTML webpage. compScript.js: This file will contain some component functions. Just like this: Now, in your HTML, link the mainScript.js using the following command: <script type="module" src="mainScript.js"></script> As you can see, unlike normal script tags, we are not only passing the source link, but also the type which is set to “module”, to notify the browser that this script is in modular form.

 Adding function inside the component file

Now, to display modularity, you are going to create some variables/functions in the component script file “compScript.js” and export them inside the mainScript.js. Inside the compScript.js create the following function that will print out 5 numbers: function printNumbers (num){ for(let i = num; i <= num+5 ; i++){ console.log(i); }} Your component script file will look like this:

 Exporting And Importing features

Now to access this function inside the mainScript.js file you need to export this function from the compScript.js file. You can do that by putting the keyword export behind the function just like this: Now, to use it inside the mainScript.js, we need to catch this export using the import function. You can do that by using the following syntax: import { function-name } from "scriptSoruce.js; In our case, this line would change into: import { printNumbers } from "./compScript.js"; Now to use this function in our main script file, you can simply call the function as we call any other function: printNumbers(5); The mainScript.js will look like this: Save the file, and refresh the HTML, and head over to the developer console and you will see the following output: And if you pay close attention to the output inside the console, you will see: Even though you only linked the mianScript.js with the HTML page, our component was successfully executed. Therefore, you can say that you have successfully implemented the concept of componential modularity.

 But wait, there’s more!

Imagine you are exporting multiple functions like: export function printNumbers(num) { for (let i = num; i <= num + 5; i++) { console.log(i); }}export function NamePrinter (){ console.log("John Doe")}export const age = 22;export function printJob(){ console.log(`Auditor`);} Writing the keyword export with every element that you want to export is not a good approach, what you can do is, is at the end of the file, write one line command, that will export the functions and the variables that you want to. You do this by writing the following line: export {printNumbers , NamePrinter , age ,printJob}; Your compScript.js will look like this: Similarly, to import all the functions and variables with the export keyword from a file, you can use the asterisk “*” symbol as shown below: import * as comp from "./compScript.js"; The asterisk symbol “ * ” means that you want to import all the exports of the file under the name “comp”, To use the function and variables that we just imported, use the dot operator along with the name of the function/variable: comp.NamePrinter(); If you were to use all the exports from the compScript.js file, then you will use the following code: import * as comp from "./compScript.js"; comp.NamePrinter(); console.log(" Age is: " + comp.age); comp.printJob(); comp.printNumbers(2); Then your mainScript.js will look like this: Save the files and refresh the webpage and you will see the output inside the console as As you can see, we successfully utilized every export from the compScript.js inside our mainScript.js file.

 Conclusion

Modules help us divide our web applications into smaller, concise, and manageable parts; modularity is achieved by dividing the script into various components and using the import and export features option introduced in ES6. To demonstrate this, we set up a basic HTML page, created two different script files, and gave some features inside the component file. Afterwards, we used them inside our main script file. We also learned different ways of exporting multiple features and importing all the features at once.

While and Do…While Loops

If you are learning to become a programmer then you should know this fact that one of the most commonly used programming concepts is Looping or Loops. Loops are available in every programming language and one can even say that no programming language is complete without providing the loop functionality. But, what exactly is a loop?

 What is a loop

The concept of looping is pretty straightforward, that is to run some specific instructions repeatedly for a fixed number of times or until a certain condition is fulfilled There are various types of Loops available in JavaScript but we are only going to be focusing on the While loop and do-While loop.

 The While Loop

The While loop repeats a chunk of code after checking a condition, if the condition that is given to the While Loop in its parameter is True then it will execute the block of code placed inside it. Otherwise, it will not go inside the body. However, we must keep this thing in mind. Having a wrong condition, or having no condition can make the loop run forever and eventually crash your browser or your code editor.

 Syntax of the While loop

The syntax of While loop is as: while(condition){// Body of the while loop}

 Working of While Loop

To understand the working of the While loop, we can take a look at the flowchart below:

 Example

Let’s take an example where you want to print from number 1 to number 10. Doing it the traditional way, we’ll have to use 10 statements to perform this task. The statements would look something like this: console.log(1); console.log(2); console.log(3); console.log(4); console.log(5); console.log(6); console.log(7); console.log(8); console.log(9); console.log(10); The output is shown in the snippet below: Writing 10 lines to print 10 numbers might not seem like that much of a big deal. However, imagine if you were assigned a task to print a thousand numbers then it would look like a really big task. Let’s take a look at how we can do this using While Loop:

 The code snippet is as

i= 1;while(i<= 10){ console.log(i); i++;} The output is as: We have accomplished this task by using only 5 lines. Even if we wanted to print the first thousand numbers we would have to use these exact 5 lines and change the condition to: while( i <= 1000) Now we have a better understanding of how the while loop works, but we still haven’t found a basis on which we will differentiate it from the Do-While loop. So, for that let’s try and make a code that fails the condition on the very first try. Like this: value = false;while(value){ console.log("I am the body of the while loop");} console.log("end of program"); This program doesn’t give any output to the console because when the while loop checks the condition and decides that the condition is false, therefore, there is no need to go inside the body of the loop, that is why the line inside the loop does not execute and the line outside of the loop executes. Just like this: That is it for the while loop, we have a clear understanding of the working of the while loop now.

 The Do-While Loop

The Do-while loop is very similar to the While loop with the only difference being that it first executes the body of the loop one time and then checks the condition for further iterations of the loop. Having a wrong condition or a boolean value True in the condition parameter can cause the loop to run forever and crash your system.

 Syntax of Do-While loop

The syntax of the Do-while loop is as: do{// Body of the loop here}while (condition);

 Working of Do-while Loop

To better understand the working of the Do-while loop, we are going to look at a flowchart.

 Example

Let’s take the same example of printing the first 10 numbers but this time we will be doing it using the Do-While loop. The code snippet is given below: i=1;do{ console.log(i); i++;}while(i<= 10); The output is : The working is, as you can see, pretty similar to the While-loop. But, let’s differentiate between both of the loops by trying to perform the example we did in the while loop’s section with a condition that is always false: value=false;do{ console.log("This is inside the body of the Do-while Loop");}while(value); console.log("This is outside the body of the loop"); The output is as: As you can see, we are executing the command which was present inside the body of the loop even though the condition was never true. That is because of the reason that the Do-while loop executes the body of the first and then checks for the condition, meaning that the code or instructions inside the body are executed once no matter what the condition returns.

 Conclusion

The while and Do-while loops are essential to any programming language but differentiating between them can be a little confusing. We have learned how both of these loops work, their syntax, and their differences. With this, we hope that you can use these concepts and develop your dream application.

How to append HTML using JavaScript?

Writing HTML code is easy, but when it comes to dynamic changes over the pages like appending HTML, you need to use unusual strategies. JavaScript is a powerful language to get such kinds of jobs done. You can easily use JavaScript to put the HTML code inside the template. We will discuss this in this write-up. Through JavaScript, there are two ways to attach HTML code to a div tag. Using innerHTML property Inserting adjacent HTML using the insertAdjacentHTML() function

 Using innerHTML attribute

To use the innerHTML property to attach code to an element (div), first pick the element (div) where you wish to append the code. Then, using the += operator on innerHTML, add the code wrapped as strings. Here’s the syntax of the attribute. HTMLelement.innerHTML += "Insert your code here" Let’s take an example of this. First, we are going to be referring to the HTML element by using the property : document.getElementById(); Therefore, let’s create a <div> and put a <h1> tag and a <button> inside it. <div id="test"><h1>This is a LinuxHint Tutorial</h1><button onclick="buttonPressed()"> Append Paragraph</button></div> As you can see, we have given an id of “test” to the div tag and placed the text that says “Append Paragraph” inside the button. With these, we have the following result on the screen

 JavaScript code:

We have a button linked to a function named “buttonPressed()” in the script. But, we have not defined this function, and this button does not do anything. So, let’s create this function in the script that would add a paragraph in this div and count how many times we have added this paragraph. Take a look at the following code. i = 1;const buttonPressed = () => { document.getElementById("test").innerHTML +="<p>Yoo have append this paragraph " +i+ " times"; i++;} Note: We have created a counter variable “i”. This will be used to keep a check on how many times have we append this paragraph inside the div tag. Now, if we run the code and press the button we get: Note: This technique essentially removes all of the div’s content and replaces it with new stuff. Any listeners linked to the child nodes of that div will be lost as a result. That is why we always concatenate it.

 Using AdjacentHTML method

The insertAdjacentHTML() function can also be used to attach HTML code to a div. This method is comes in handy when it comes to appending HTML at some specific place. So it takes two parameters in this method: The location (in the document) where the code should be inserted (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’). afterbegin – right after the HTML element mentioned but inside the tag. beforebegin – before the HTML element mentioned afterend – after the closing tag of the HTML element beforeend – inside the HTML element but before the closing tag You must surround the HTML code you wish to add, inside the quotes. This is the general syntax of the method HTMLelement.insertAdjacentHTML(‘LOCATION‘, ‘HTML CODE’); Let’s use the previous example. The same HTML code. However, this time the script would be slight different as: HTML Code: <div id="test"><h1>This is a LinuxHint Tutorial</h1><button onclick="buttonPressed()"> Append Paragraph</button></div> Note: Since we are using the previous example, the HTML code is exactly the same. JavaScript Code: i=1; function buttonPressed() { document.getElementById("test").insertAdjacentHTML("beforebegin","<p>Appended " + i + " times Before Div<p>"); i++;} Note: We are using the “beforebegin” property to append the <p> tag before the start of the div. Output: That’s it, you have learned how can we append some HTML code through JavaScript.

 Conclusion

There are two methods that you can use to append the HTML code into a webpage. The first method is by using innerHTML while the second method is by using the AdjacentHTML method. In this article, we have taken examples of both the innerHTML and AdjacentHTML methods to append the HTML code into a webpage.

How to run JavaScript through the terminal

JavaScript is a handy language to practice in modern-day tools and technologies. If you start learning JavaScript from now on, it can lead you to a powerful base for web-based client and server-side scripting. Unlike other languages like C or Java which need to be compiled before running, JavaScript is the interpreted language that does not need any compiler. If you have written a few lines of code and you’re not able to figure out how to see the results of it or how to run it! This is the write-up in which I’ll be explaining how you can easily run the JavaScript code through a terminal or command prompt. You may run a JavaScript console in a terminal or other command-line interface using Node.js(an open-source, cross-platform runtime that executes JavaScript outside of a web browser).

 Running JavaScript in Terminal

This is how you can easily run JavaScript through your terminal/Command prompt Install Node.js Run the JavaScript code using the ‘node (filename).js’ command

 Installing Node.js

Visit the Node.js website to download the latest version of Node.js depending on if you’re using Mac, Windows, or Linux, and install it in your system. Note that download the stable version of the Node.js. After installing the Node.js in your system, open the command prompt and type: $ node --version You will see the following output: Note: If you want an in-depth guide on how to install NodeJs then you can visit this extensive guide.

 Running the JavaScript file

Let’s see how we can run our JavaScript file in the terminal using node. First of all, create a file demo.js or whatever name you want to give to your JavaScript file like so: Write some JavaScript code in it. let Name = "Shahroz Azam" console.log("Hello world, My name is: "+ Name) After writing the code inside your JavaScript file, now prompt yourself to the folder where you have created that JavaScript file, for my case it’s inside E:\\ directory. So, use terminal to first navigate it to E: drive: Type the following command: $ node demo.js You will see the following output: Congratulations you’ve successfully run your first JavaScript file inside the terminal.

 Conclusion

By installing Node.js on your system, you can run JavaScript code in the terminal. After installing, you can use the node command with the name of the JavaScript file and that will be it for running the JavaScript in the terminal. In this article, we have seen how we can install Node.js and how we can use Node.js to run our JavaScript code in the terminal.

How to replace an HTML element using the replacewith() method?

JavaScript is widely used in web page development and its libraries like JQuery are very handy. In old technologies, it was nearly impossible to change or replace an HTML element using server-side scripting languages, we were only able to change the content inside the element through the backend languages. But thanks to JavaScript, it made life easier and allowed us to dynamically change the element of the webpage. It provides various methods to achieve this functionality but the one we are going to look at in this post is the JQuery’s replacewith() method. Let’s take a deep look at this method.

 JQuery replaceWith() Method

In jQuery, the replaceWith() function is used to replace chosen components with new ones and it returns the components that have been replaced. The replaceWith() method syntax is mentioned below. $(element).replaceWith(newContent, (idx)=>{})

 Arguments Explanation

Here’s the explanation of the arguments of replacewith() method newContent: It is the content that will be used to replace the parts that have been chosen. (idx)=>{}: It’s the function that returns the replacement content. It also has an index of arguments and this index parameter is used to return the index position of the element. To better understand how to utilize the replaceWith() function, consider the following examples.

 Example #1

Suppose, we have a <div> element in our HTML whose id is “element1” and at the click of a button we want to replace it with the <p> tag. The HTML part would be like this: <div id = "element1"> This text is a div tag</div><button id = "btn"> Replace </button> And at the click of a button, we want to replace the <div> Now, to completely convert the <div> tag and its content to the <p> tag, jQuery’s code will go like this: $(document).ready(function(){ $("#btn").click(function() { $("#element1").replaceWith("<p> Element Replaced :) </p>");});}); In the above example, we are simply first fetching the HTML element by using the IDs of the button and div tag and then replacing the <div> tag with the <p> tag using replaceWith() method. Output You can witness that the element was successfully replaced.

 Conclusion

JavaScript’s replacewith() method is used to replace one HTML element with some other element according to the requirement. This replacewith() method takes two arguments, the first argument is the content that you want to be replaced with while the second argument is used to return the index position of the content that you want to replace with. In this article, we have discussed the examples of replacing the old content with the new one using JQuery.

How to read local files

JavaScript is a high-level web programming language that gives web pages the ability to think and act. JavaScript offers developers interactivity with files that are present on the developer’s local system. Interactivity with the files can be of different types,for example, uploading a file to a server or uploading it with restrictions. There are multiple ways of opening and reading local files, most common being using the in-built File-system/promises API –“FS” API,or by using the HTML select file attribute of the <input> Tag, or even using some external package and then trying its method. So, in this post, we will show you how to read local files by using the Fs API and by using The HTML select file Attribute.

 HTML5 FileReader API

HTML5 introduced a consistent mechanism to deal with local files by introducing the File Reader API specification. The File Reader API can be used to provide a thumbnail preview of photos when they are transmitted to a server as well as allowing a web application to store a file reference even if the user is not connected to the internet. Using the event handlers of JavaScript and the File Reader API we can asynchronously read a file. The file Reader API offers us four built-in methods that we can use to read files asynchronously. The first built-in method is the FileReader.readAsArrayBuffer() which reads a local file content but returns an ArrayBuffer that has the file content. Then comes the FileReader.readAsDataURL() that returns a URL of the data from a local file. The FileReader.readAsBinaryString() returns the content of the local file in a string format and the most used built-in method of FileReader is the FileReader.readAsText() that returns the content of the local file in a text string format or we can say in a human-readable form. Now that we know what FileReader API is, let us set the HTML environment for a user to select a file that he/she wants the browser to read.

 HTML Select File

HTML is a hypertext markup language that is used to give structure to our web pages. We will use HTML to make the user select a file and then we will use JavaScript to read the file’s content. The HTML code is given below: <!DOCTYPE html><html lang="en"><head><title>Read A File</title></head><body><input type="file" id="myFile"><p id="fileOutput"></p><script src="code.js"></script></body></html> In the above code, we have initialized an input tag with the type of file and given the attribute id which will be used to reference this element in our JavaScript file. Next, we have initialized a p tag in which our content of the file will be posted once the user selects a file. In the end, we use the script with the src attribute in which we have referenced a file code.js that will contain our JavaScript code.

 JavaScript Read File Functionality

We are done with HTML, so now let’s move on to JavaScript to achieve our purpose of reading a file. For this purpose, we will use the File Reader API built-in method readAsText(). The JavaScript code is given below: var myFile = document.getElementById("myFile"); var fileOutput = document.getElementById("fileOutput"); myFile.addEventListener('change',function(){ var fileReader=new FileReader(); fileReader.onload=function(){ fileOutput.textContent=fileReader.result;} fileReader.readAsText(this.files[0]);}) In the above code, first, we get the reference of the input file and the p tag we set in the HTML using their id attribute. Next, we have added an event listener of change so that whenever a user selects a file or chooses a file, the function present in this event handler will start executing. Inside the event handler function first, we initialized the FileReader() object with the new keyword. Then at the completion of the fileReader function we are just posting the result of the file read in the fileOutput variable which is indeed the p tag. In the end, we are reading the file with the help of the built-in method of FileReader that is readAsText() and passing an argument to mention reading the file that is on the first index. We are doing this so that the user does not select multiple files and even if he did select multiple files then the FileReader will just read the first file among them. Let us now select a file. For that purpose, I have created a text document and wrote two lines in that file. The output of the file content is given below: Let us now select this file from HTML and see whether we can see the file content or not: We have successfully chosen a file and read its content and then printed that content.

 Conclusion

HTML5 provides a FileReader API through which we can read file content. The FileReader API gives us four built methods that we can use to read a file the way we want. The readAsArrayBuffer() reads a file and returns an ArrayBuffer of the file content, readAsDataURL() reads the file and returns a URL that has content of the read file, readAsBinaryString() read a file and returns raw binary data of the read file and the last is the readAsText() which reads a file and returns the content of the read file as a text string that is in human-readable form. In this post, we discussed how to read a local file by first implementing how to select a local file using HTML, and then when we select that file we read the file content using JavaScript.

How to Open URL in New Tab using JavaScript?

This is very common to navigate users from one page to another when you are developing a web application. Normally when you are using HTML, the anchor tag <a> is used to add links to navigate to other pages. By default, the browser does not allow you to switch to the new tab when clicking a link. So we need to define the attribute on the link which will direct the instruction to the browser that it needs to open that link into a new tab. While we are working in HTML, we can put the “_blank” value to the target attribute and the URL link will be opened in a new tab. But how to achieve this job when you are using JavaScript. We will talk about how to open a URL in a new tab using JavaScript in this write-up.

 Opening URL in a new tab using HTML

A hyperlink to another page is created with the anchor element <a> in HTML. We use the href property to give the URL of the page we want the user to prompt to and the “_blank” value to the target attribute of the tag for opening the link in a new tab. A traditional method to get this job done is as follows: <a href="https://linuxhint.com/" target="_blank">Linuxhint Website</a> Now, if you click on the link “Linuxhint Website”, the “linuxhint.com” will open up in the new tab. This was a traditional way to open a link in a new tab. Now we are going to have a look at how we can achieve this by using JavaScript

 Opening URL in a new tab using JavaScript

To open a URL in a new tab using JavaScript, the window.open() method can be utilized. The technique is pretty simple. We just have to pass two arguments to the window.open() method. One is the URL of the web page. The second argument is the same as the target attribute in the anchor tag <a> in which we specify where we want to open up the URL e.g. “_blank”. window.open("URL", "_blank"); Let’s think of an example, in which we want to open the “linuxhint.com” website in a new tab with the click of the button. <button onclick="newTab()">Linuxhint Website</button> After creating a button in HTML, we have called a function named “newTab()”. Let’s define it in our JavaScript code where we will use the window.open() method and provide it the URL of the “linuxhint.com” website and “_blank” value for opening the website in a new tab.

JS

const newTab = () => { window.open("https://linuxhint.com", "_blank");} Let’s execute the code and see the results. When we click on the button “Click” it opens the “linuxhint.com” in a new browser tab.

Additional Methods

Here are some additional properties that you can attach while opening a URL: _blank: The URL is opened in a new tab. _parent: The parent frame is loaded with the URL. _self: The current page is replaced when this property is called _top: Any loaded framesets are replaced by the URL name – the widow’s name.

 Conclusion

For opening the URL in the new tab, you have to put the _blank value to the target attribute of the anchor <a> tag in the HTML. You can also select the anchor tag using a JavaScript selector and add the target attribute with _blank value. In this post, we have seen how we can use the window.open() property at the onClick event of the button for opening the URL in the new tab programmatically through JavaScript.

How to convert a JPG image file to PNG image file using Node.js

One of the ways of learning any programming language is to develop small projects or in other words experimentation. Surely, you can find online tools that would convert a JPG image to a PNG image, but we don’t want to do that as a programmer. What we want is to learn how this automation process is done – the process of converting a JPG into PNG using a piece of code – and that is exactly what we are going to do today using NodeJs In this tutorial, you will learn how to convert images from JPG to PNG and PNG to JPG format by using the node js “Jimp” package.

 What is “Jimp”?

Jimp is a JavaScript-based image processing library with no native dependencies. It enables you to perform a lot of amazing things with photos in a simple way.

 Installing Jimp Package

Since JIMP is a node package, you must have Node installed in your system in order to install any package like JIMP. First, install Node on your system and after that install the JIMP package before using it, otherwise the exception with the msg “Cannot find module ‘jimp‘ ” will be generated in the console. You may use either the NPM or Yarn commands to install it: To install Jimp using NPM package manager, execute the command: $ npm install jimp Or if you want to install “Jimp” using Yarn then execute the command: $ yarn add jimp Now you are ready to write some code to perform the conversion.

 Converting from JPG to PNG

Let’s start by converting a .jpg file to a.png format. Ensure that the image file is located at the root of your project directory First, import the “Jimp” package in your JS file and assign it to any variable like “Jimp”. const Jimp = require("jimp") After that, to convert the picture into your desired PNG file type use the Jimp.read() method. The jimp.read() is dependent on two arguments, one is the path of the image file and second is the callback function which returns the converted image file or error. The complete Jimp.read() method would go like this: Jimp.read("image.jpg", (error, file) => {if (error) { console.log(error.message) } else { file.write("new-image.png") }}) After writing all this piece of code, let’s execute it and see the results. Take a look at the snippet below, there is no ‘new-image.png’ in the directory: Now when I run the script, this will create a “new-image.png” file in the same directory. Does that make sense? Cool! Now let’s move to the next part and try to convert a PNG file to JPG file in an example.

 PNG to JPG Conversion

To convert a JPG file to a PNG file, we do not need to change anything in the Jimp.read() method instead of providing the PNG file. const Jimp = require("jimp") Jimp.read("image.png", (error, file) => {if (error) { console.log(error) } else { file.write("new-image.jpg") }}) As you can see there is no “new-image-2.jpg” file in the directory. Why not try running it to examine the output. After running the script, Jimp will automatically generate the “new-image-2.jpg” file in the same directory.

 Conclusion

Node.js uses a package named Jimp for converting the JPG file into PNG format. Simply import the Jimp package and call the read method on Jimp by using Jimp.read. The Jimp.read() method takes two arguments, one as the name of the file and the second argument is the callback function that handles the response of the function. In this article, we have discussed how we can convert a JPG to PNG and PNG to JPG as well.

Creating a Simple Discord Bot with Node.js

Discord has become the application of choice for many internet users specifically for its VOIP features. During the pandemic, a lot of work was shifted to online (“work from home”) and thus increased the popularity of Discord and Discord servers. With increasing popularity came the increasing numbers of Discord bots. Bots in general are nothing but automation of various tasks. Anyone familiar with Discord is familiar with what a Discord bot is. Maybe the most well-known Discord bots are the music playing bot (music bot, rhythm, groovy, etc.) These bots allow you to play music by pinging it with a song name and then they search for that specific song, join the channel from where it was pinged, and start playing that song. The purpose of this post is going to be creating your first Discord bot, using the well known Discord.js library. Let’s get into building our first Discord bot.

 Prerequisites

Almost every task that we do online requires some sort of prerequisite. The prerequisites for creating a Discord bot are as follows: Node.js v10 or higher (latest version >16.0 is preferred) Discord account and a Discord server Some basic knowledge of the terminal (not compulsory)

 Step 1: Creating a bot application on Discord.com

We start by creating\registering our bot on discord.com. If we wish to control the bot using our code, we need to first register the bot under our Discord account. Go to Discord.com and then Applications. After logging in to your Discord account, you’ll be taken to your Discord dashboard. Click on “NEW APPLICATION” from the top right side of the browser window. Next, you’ll see a screen where the name of the application would be demanded from you. For this post, we’ll call out the bot “my-greeter-bot”. Next, hit on the button that says “Create”. This will create the Discord API application. This will create the bot as an application under the name given by you. In our tutorial, it is called “my-greeter-bot”. Now you’ll be able to notice client ID and other information about the bot application. Like the image below. What we want is to give this bot permission and invite it to our server and get the TOKEN. For that, click on the “Bot” tab from the left sidebar. Now click on add Bot on the right side and our bot will be created. Once the process has finished creating and setting up the bot on the Discord server, you’ll be able to see its information. Click on the COPY TOKEN option on the screen, this will copy the authorization token code, now save this code somewhere in a text file or write it down. We will require this code later on in the tutorial to connect our VS Code (or any editor of your choice) to the bot:

 Step 2: Defining Bot permission and adding the bot to our server

The next step is to define the permission we are going to ask from the server to which our bot will be added. Explore the OAuth2 segment as shown in the image below. Here we can characterize the degree for our bot. Check the “bot” option from the list. From the permission, listen beneath it, select Send messages, and Read Message History as well. We’ll have our bot go through messages in the text channel and reply to those messages which meet the criteria determined by us. Copy the link and open it. There you’ll see a pop-up box that will ask you about which server to ask the bot into. Select your desired server and voila, you have added your custom bot to your desired server.

 Step 3: Setting up Visual Studio Code

Visual studio code isn’t a necessity, it’s up to you to choose which code editor you want to use. For this post, we’ll be utilizing visual studio code: This project depends on two major dependencies. Dotenv Discord.js So, let’s create a node project and install these dependencies: Create a folder and using the terminal start the node project by using “npm init”.Install dependencies by typing “npm install dotenv” and “npm install Discord.js” To complete the installation of the dotenv dependency, create a file in the root of the project with a “.env” extension. To do this, right-click in the explorer in visual studio code and create a new file. And name it as “.env” just like it is shown in the image below. Once the file is created what you are going to do now is to add one environment variable called TOKEN to the file like: TOKEN=my-unique-bot-token Make sure to replace “my-unique-bot-token” with your bot token.

 Step 4: Index.js (exploring Discord.js)

We are going to create another file just the how we created the “.env” file. and we are going to name this file “index.js” just like this: After this file has been created we can start working on coding our bot now. Start by requiring “dotenv”, by doing that we are going to be able to use various environment variables, but in our case, it is only going to be the TOKEN variable. In order to access this variable, the one we have created in the .env, we use the line: const TOKEN = process.env.token ; And lastly, to link our code to the discord bot which we have just added to our discord server, we use the command bot.log(TOKEN), the block of code is as: require('dotenv').config();const Discord = require('Discord.js');const bot = new Discord.Client();const TOKEN = process.env.TOKEN; bot.login(TOKEN); The next step is to set up a listener, which only listens for the “ready” Event: Knowing node.js, we can listen for events. The ready event automatically launches once we have connected to the bot. bot.on('ready', () => { console.info(`Logged in as ${bot.user.tag}!`);}); To test if the bot you are getting connected to or not. Type the following command in the terminal of the root directory of the project “node index.js”. You should see something like this.

 Step 5: Listen for “message” events

We now know that our code is connecting to the bot. All we need to do now is to code a simple message listening event and reply to that message. This would mean that the bot can go through messages in the text channel and reply to those messages. These messages would generally contain requests by the users. This message listening event would make our bot able to go through the text messages in the message channels, and will even allow the bot to respond to those messages as a “reply”, to do that append the following code in the index.js file. bot.on('message', msg => {if (msg.content === 'ping') { msg.reply('pong'); msg.channel.send('pong');}}); The code above is a listener on any message in a text channel. What the bot does every time a message is sent in a channel is that it reads that message and searches it for the string “ping”. If the channel has a message that just has the word ping in it, the bot replies with pong. After that, we need to reply in a channel, and to do exactly that we use the command: msg.channel.send(‘pong’). The above code can be broken down into: msg.reply: tags the initial user who has sent the message msg.channel.send: sends a message to the channel without tagging anyone I guess we now know the general concepts of the commands above. Fire up the code using the node index.js command (just like we did before) and send a message ping to the general text channel. That’s it. You have created your first ever Discord bot, which reads and replies to messages.

 Conclusion

Discord bot seems nothing less than a work of magic at first. But, once you know how a Discord bot is created, it won’t seem like the work of a magician. True, at first it all seems very overwhelming, but thanks to the Discord.js Api, it all becomes easy. There are a ton of different permissions to be uncovered and implemented. Hoping this tutorial was useful to you, as it was only a first step towards creating your own ultimate bot. To explore Discord.js API and its package then you can head over to the Discordjs.guide website. All the best on building your very first Discord bot, and taking more steps towards greatness.

How to upload a file in React.js?

File uploading in an application is an essential component that every developer takes into account while developing an application or webpage. File uploading simply means that a user uploads a file which can be an image, video, or document, just like we upload images or videos to our Instagram and Facebook. So, let’s see how to upload a file in React.js in this post but before going to the process let us see what React.js is. React.js is a popular front-end JavaScript library for creating and designing user interfaces for single-page apps. The most intriguing part of React.js is that with the help of it we can change data on a web page without reloading the entire web page or application. React.js features include simplicity, fast and scalability.

 PreRequisites

Before going on the coding part of how to upload a file in React.js let us first create a React.js project. For this purpose open Visual studio code terminal or Windows command prompt and execute the below-mentioned command which will create your app with the name of fileupload: $ npx create-react-app fileupload The next step is to change the directory to the file we just created which is fileupload. $ cd fileupload The next step is to install Axios which is a promise-based HTTP client and will help us in sending the selected file to a server. To install Axios execute the below given command in the terminal: $ npm install axios Now that we are done with creating the basics of our application and installing Axios let us open the App.js file and modify that file to achieve file uploading in React.js.

 File Uploading in React.js

The first part is to design your webpage for file uploading. For this, we will be needing a header and two buttons that are; Choose File and Upload. When the user clicks the Choose File button, he/she should be redirected to choosing a file from the computer system and when they click the upload button, the file that was chosen should be uploaded to the server. Also, it should be noted that we need an event handler that will listen to any changes that are made to the file hence we used onChange which is referencing the onFileChange function. Now whenever the user selects a file, the onFileChange function will be triggered and the state will be changed accordingly. Now that we have selected a file and handle the state change, let us now send the file to a server in an object named FormData for which we installed Axios earlier. // importing axios importaxiosfrom'axios';// importing React and componentimport React,{Component} from'react'; classAppextendsComponent { state = {// file state is null in the start selectedFile: null };// When user selects a file, set state onFileChange = event => {this.setState({ selectedFile: event.target.files[0] }); };// when user uploads file this function should execute onFileUpload = () => { constformData = newFormData(); formData.append("myFile",this.state.selectedFile,this.state.selectedFile.name );// console log uploaded file details console.log(this.state.selectedFile);// user send req to the server axios.post("api/uploadfile", formData); }; render() {return (<div><h1>Let's Upload Files using React.js</h1> <div> Upload</button> </div> </div> ); } } export default App;

 Conclusion

React.js is a front-end library handled by Facebook and using it we can develop very fast and scalable web applications. In an application like Instagram or Facebook, uploading files is an essential feature and every developer should know how to develop an application that has the upload files feature. To get a grip on the file uploading concept, we demonstrated how to upload files using React.js in this post and provide you with the code and screenshots on how it will work.

Top 10 coding projects for beginners

JavaScript is a well-known scripting language that is used in websites in order to validate, build intuitive illustrations, deliver dynamic content, and considerably much more. JavaScript gives our web applications the ability to think and act by making them interactive and dynamic. If you are using JavaScript in your websites then clients can interact efficiently to see all intuitive components on the web page. Now we rapidly enlist a few significant elements of JavaScript. It can be used on both sides i.e. server-side or client-side to build interactive web content. dynamic functionality for better user experience It has object-oriented features and lightweight scripting language Cross-platform language There are several JavaScript projects available over the internet but in this article, we will demonstrate the best 10 JavaScript projects for beginners that turn out best for you.

 Why JavaScript Projects:

Well, a good knowledge of JavaScript can present great career opportunities if you are looking forward to earning by being a programmer with the profession. And as they say, “Practice Makes a man perfect”, so these projects are really good to understand javascript more thoroughly and quickly. So, even if you are a complete beginner, developing these projects would help you grow a lot. As these are all going to be beginner-level projects. With that said, let’s begin.

TO-DO List

Starting off, we have the simplest thing in this whole list. To create a TODO-List. The functionality of this To-Do List is going to be very simple. It’s going to show the user a list, much like a tabular form with two columns, one for the task and the other one for the checkboxes. The user will have the option of adding items to the List. Each item will have a check-box in the list right next to it. When the user clicks on the check box, it would get marked, and the Item on the list gets a line passing through the text showing that this item has been completed.

JavaScript Calculator

The next project is to create a simple JavaScript-based Calculator. This Calculator should have all the basic math DMAS functions. The UI of the Calculator should have pressable buttons on it. And a Screen where every input is displayed and the output of every operation should also be displayed on it. Also, The calculator should follow the DMAS rules, which stand for division, multiplication, addition, and then lastly subtraction.

Hang-Man

One of my favorite games of childhood, the hangman. It’s a simple guess for the word game. The system randomly selects a word and shows some blank dashes equal to the size of the word to the user. The user has to guess the word under a certain amount of tries or else the user will die in-game. If the user successfully, the hangman lives to see another day, else He gets hanged on the noose.

Weight-Conversion Tool

Next up the list is a very simple project, ”Weight Conversion Tool”. The user chooses the unit of weight to convert from and the unit into which the application is going to convert the weight into. After that, the user is shown an input bar where the user inputs his weight and the converted weight is shown to the user.

Tic-Tac-Toe

This is when things start to get much more interesting. You are going to develop graphical tic-tac-toe. A game for 2 users. One will be named as player “X”, and the other will be named as player “Y”. The rules for the game would remain the same as they are in the real world. Three same signs in any direction would declare the winner. The winner who wins would be highlighted on the screen.

Weather-Application

Let’s get familiar with the use of API. What we are going to do now is develop a very minimalistic whether application. That would track the location of the user, and depending upon the weather conditions on the outside and the Data from the weather API, it will give us the exactly reading of the weather

JavaScript Validation form

As we all know, javascript became famous for its use in building web applications. Well, the most important aspect of web applications is the validation forms. So, we need to build a form with all sorts of validation put into it. These validations should include, verification of a valid email address, 13-digits of a phone number. Cross-checking passwords and confirming passwords and much more according to your need.

Rock-Paper-Scissor

The next project would be to bring back another game from the back of our memories into the digital world. The user has to play against a computer and he will be shown an option to choose what he wants to be put in next turn, Rock, Paper, or maybe scissor. Meanwhile, the computer would randomly choose any one of the signs and use it in the match. The winner of the match will high-lighted.

 To Create a javascript slideshow

To those who are into web or app development, this is a very important one. To create a javascript slideshow. The images will change with a small transition effect and the whole widget would work as a little carousel.

 To redesign an already existing Web template

Well, the last project of this is to take a web template from the internet and make amendments to it. Why you may ask, well, to create web pages you must know how different elements on a web page work. This is a must faster and exceptional way of learning web development. Moreover, if you like to make it more of a challenge then make the whole web page responsive on multiple screens.

 Conclusion

To become good at something you must practically use it and get the feel of it. Hands-on experience is a lot more valuable than anything else. Well, we have gone over the key factors of 10 different beginner-level projects. By completing all these 10- projects you’ll gain a keen understanding of the practical use of JavaScript. This way, you can become a good programmer and can build a career if you choose to pursue it.

SyntaxError: missing ) after argument list

While developing software, the probability of syntax errors is high. If you used incorrect pre-defined syntax then you might face an exception. Syntax errors are distinguished while compiling or parsing source code. This type of syntax error arises when an error such as typing error or missing operator is detected in a function. This can happen either due to a missing operator, typo error, or an unescaped string. Generally, JavaScript functions are dependent on brackets. So, in simple words, we can say that JavaScript is dependent on brackets to recognize the start and end of function calls. This article explains the meaning of syntax error and it is important to understand why this error is triggered. In order to understand the issue and fix the problem, a walk-through has to be performed. “The missing after argument list” message shows that there is a possibility of syntax error within the method. This is probably due to the comma used erroneously where the list of arguments is not followed by other arguments. For example, if you forgot to enclose the JavaScript function, then it triggers a syntax error. These types of error messages are shown in the browser. (Edge Error) SyntaxError: Expected ‘)’(Firefox Error) SyntaxError: missing ) after argument list Now we are going to provide a few examples. In the example below, we used Math.random() function to generate rapidly random numbers. But this function doesn’t work as the “+” operator is missing. Therefore, an error is triggered. console.log('Generating Random Number: ' Math.random()); Output The above error was triggered due to the missing “+” operator in the console.log function. So, you can easily fix this bug by inserting the “+” operator in the console.log function as shown in the example below. console.log('Generating Random Number: ' + Math.random()); Output The concatenation of two strings is illustrated in the example shown below. But the document.write() function doesn’t work as the “+” operator is missing. Therefore, an error is triggered. <!DOCTYPE html><html><body><script> var string1 = 'You are learning '; var string2 = 'Syntax Error: missing ) after argument list'; document.write(string1 string2);</script></body></html> Output Above mentioned error was triggered due to the missing “+” operator in the document.write() function. So, you can easily fix this bug by inserting the “+” operator in document.write() function as illustrated in the below-mentioned example. <!DOCTYPE html> <html> <body> <script> var string1 = 'You are learning '; var string2 = 'Syntax Error: missing ) after argument list'; document.write(string1 + string2); </script> </body> </html> Output In the example below, we simply concatenate two strings by using the “+” operator but an “invalid or unexpected token” error is triggered. This error is triggered due to a typo error. console.log('"Learning" + "missing ) error""); If you want to fix this bug then you have to insert “ “ as shown in the example below. console.log('"Learning" + "missing ) error"');

 Conclusion

It is significant to note that as with other syntax errors, the error of missing parenthesis ‘)’ after the argument list can’t be caught by the ordinary try-catch block. This problem related to syntax is resolved through JavaScript. This generally implies that it doesn’t appear at the execution point where it can proceed toward the catch part of the block, since it doesn’t have the foggy idea of how to parse that effectively. This suggests that Syntax Errors are the major challenge. In this article, we have learned the concept of syntax error and also learned the reasons why this error is triggered. Then we went through the examples which clearly define how to fix this syntax error of missing parenthesis ‘)’ after the argument list.

JavaScript NaN | Explained with examples

If you have worked in other programming languages like Java you will know that the null pointer doesn’t point to anything and is simply as 0. However, when we come to JavaScript we find that null is a primitive value and the data type of null is an object. An object is something that has some properties and attributes. Then comes a global object which is always present in the global scope. One such example of a global object is NaN.

 What is NaN?

In JavaScript, we have the datatype number that allows us to store numbers like integers and floating-point numbers, and once a special value included in a number is NaN. NaN is a property of a global object that means it is always present in the global scope and NaN stands for not a number. If we console log the type of we will see the number data type: console.log(typeof NaN); We can also check whether a value is NaN or not with the help of the global method isNaN(): const output = 10+0/0; console.log(isNaN(output)); // true

 Equality check with NaN

It is quite interesting that when NaN is compared to itself, it returns false. We can see that NaN is not equal to any property:: console.log(NaN===NaN); //false

 What returns NaN?

Now that we know what NaN is, let us find out what operation returns NaN: If the output of a math operation is not a real number then it returns NaN for example: console.log(Math.sqrt(-1)); // NaN If you are converting a string to a number then NaN will be returned hence in short we can say that parsing fails when one converts a string to a number: const myString = 'Hello!';const myNumber = parseInt(myString); console.log(myNumber); // NaN In a+b, a and b are operands, and + is operator hence when you use undefined in place of an operand and performs some operation then NaN will be returned: console.log(undefined + 3); // NaN When you use string as an operand in any math operation it will also return NaN: console.log(("myString"/3)); // NaN When you give invalid arguments to a math function, it will also return NaN for example: console.log(Math.log2(-2)); // NaN console.log(Math.sqrt(-2)); // NaN

 Conclusion

NaN stands for Not a Number and is a property of a global object which means it has always a global scope. NaN is used to check a failed operation on some number, for example, parsing numbers, passing invalid arguments to a math function, the output of a math function is not a real number, using undefined as an operand, and using a string in a math operation. The isNan() built-in method gives us the ability to check for a value so that we can find out if it is NaN or not by returning a boolean value i-e true or false. In this post, we discussed what is NaN, the equality check of NaN and what returns NaN.

JavaScript Defer Attribute

If you have ever searched for web-development or website designing, then chances are you have probably heard about HTML. Well, HTML stands for “Hyper-Text-Markup-Language”. HTML is used in combination with CSS to develop attractive and responsive web pages. JavaScript is a programming language that enables our web pages and web applications to think and act and make our web applications interactive. The entire HTML document is scanned by the browser first for CSS, JavaScript, or any other referenced material such as an image and this process is called HTML parsing. The web browser then requests each of the resource files from the server if resources are found in the HTML. Once the web browser has all of the necessary resources, it begins constructing the page. JavaScript can be referenced by the script tag of HTML and JavaScript is called a parser blocking resource because HTML parsing is blocked by JavaScript. To solve this problem the script tag of HTML offers us async and defer attributes hence allowing us to have more control over how and when external files are retrieved and executed. In this post, we will explore what JavaScript Defer Attribute is and how we can use the defer attribute.

 Normal Execution

Let’s have a look at the impact of what happens when the defer attribute is not there. JavaScript files, by default, will pause the parsing of the HTML text so that they can be fetched (if not inline) and run. Let’s say we have a script tag somewhere in the middle of an HTML page and there is HTML code above and below the script tag: <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><!-- Some code above --><script src="code.js"></script><!-- Some code below --></body></html> The HTML parser will scan this page and when it reaches the script tag it will pause the HTML parsing and fetch the JavaScript code.js file in the script tag and then execute that file. Once the execution and fetching of the JavaScript file are complete, only then the HTML parsing continues again. This process delays the rendering of HTML and hence slows our webpage by taking some time to fully load the web page.

 What is the Defer attribute?

The defer property can only have a true value or a false value, we can conclude that it is a boolean attribute. It is an attribute that is used only for external scripts. If this property is used, it defines that the browser should not wait for the script to load. Meaning, in some cases, external scripts can take a lot of time to load, this property simply says to load the document before loading in the script. In simple words, the defer attribute does not wait for the script tag and the processing of HTML continues hence making our webpage increase loading performance. The syntax for defer attribute is: <script defer src="code.js"></script> It should be noted that the defer attribute can only be applied to external sheets/scripts when the src attribute is present in the script tag. It should also be noted that defer attribute cannot be applied to inline code. The defer attribute is similar to the asynchronous process, that is you can move to another task even when the first task isn’t completed. Example We are using an external JavaScript sheet with the name of code.js: <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><p>Before Script</p><script defer src="code.js"></script><p>After Script: will execute immediately</p></body></html> We initiated a p tag and then a script tag which references the code.js file and then again a p tag. In the code.js file, we simply console.log Hello World!: console.log("Hello World!"); We will see the following output:

 Browser Supportability

The numbers given in the table indicate which browser version was the first to implement the attribute completely.
AttributeMozilla FirefoxMicrosoft edgeGoogle ChromeOperaSafari
defer3.510.08.015.05.0

 Conclusion

Normal execution of HTML is blocked when there is a script tag. Script tag fetches an external file or link and then executes it hence blocking the normal parsing of HTML. The defer attribute is the solution as defer attribute will help us download our scripts as soon as possible without blocking the browser/HTML as it tells the browser not to wait for the script tag. In this post, defer attribute was discussed along with an example and the browser supportability.

JavaScript | console.log() with Examples

JavaScript is now one of the world’s most popular programming languages. Its popularity is not slowing down either, it is continuously growing on a daily basis, and the main reason is the fact that there are tons of frameworks and “run-time javascript” that help in building many top-notch web applications with ease. The console.log() is a basic JavaScript function that is used to display or print any message to the debugger’s console. The message can be any variable defined before (including arrays, objects, and so on) or any string. The console.log() is commonly used for testing purposes during the development phase. Syntax console.log(message) An example using a variable defined before in it. var fullName = "John Doe"; console.log(fullName); Output

 How it works

The log() is a method in the web API “API Console” which is available in almost every browser and JavaScript editor, the purpose of this method is to display anything passed into it using the parameters to the console panel and to access this log() method we use the console object with a dot-operator.

 Console Object Methods

The console object is used with a “dot-operator” to utilize quite useful predefined methods. Some examples of these methods would be as follows: assert(): Writes an error message to the console if the assertion is false clear(): Clears the console terminal / panel time(): Starts a timer (can track how long an operation takes) Parameters It accepts a parameter which can be a message (string) or any object. Return Value The return type is the same as the parameter that is passed into it.

 Examples using different types of Parameters

Now, we are going to use different types of parameters to show the working of the console.log() method. Using a String and number: First up, is an example with a simple numeric value and a string as its parameter. console.log("THIS IS MY WORLD"); console.log(2); Output The output can be seen in the image below: Using an Array: Next up, it would be an example using an array of String objects. var arr = ["Cricket", "Hockey", "Badminton", "Squash", "Tennis"]; console.log(arr); Output The output can be seen in the image below: Using an object: Now that we have used a simple numeric value, a string, and even an array of strings, it’s time to move on to Objects. var myObj = { firstname : "John", lastname : "Doe" }; console.log(myObj); Output The output of using the console.log() with an object as its parameter is as follows:

 Conclusion

JavaScript is becoming the most widely used scripting\ programming language in the world and if we want to become familiar with the modern-day programming sensation then we should know how various methods work. We have learned what console.log is, its syntax, usage, parameters, return values along with examples. We also learned how a console.log works by explaining what the log() method actually is and how the “console” object is used to call different methods defined in the “API CONSOLE” from the WEB API which is built into different browsers and code editors.

JavaScript Anonymous Functions | Explained for beginners

The function is a set of instructions that is executed whenever it is called and returns some result as its answer. Functions are created by using a particular syntax, for example you use the function keyword and then the function name and then parenthesis. Similarly, the Anonymous functions are the same but the difference is in the syntax. JavaScript Anonymous function does not have a name with its declaration and this is usually passed as the argument to the other higher-order functions. The anonymous function is basically built and used for instant function execution within a function as a parameter. When anonymous functions are constructed, they can be assigned to variables, giving you the same capabilities as if you used a name in the function declaration.

 Making use of anonymous functions as parameters to other functions

Because of its anonymous function, we can utilize it wherever we want, we often use this method as a parameter in another function as well, and here is the example of this below: setTimeout(function () { console.log('This function is being used as a parameter in JS setTimeout method ')}, 3000); In this example, we use the setTimeout() method to pass an anonymous function. This anonymous function is executed Three seconds later by the setTimeout() method.

 Immediate Execution of a function

Immediate execution of a function means that you have created a function and you want it to be executed right after it is created. You can achieve this functionality with the anonymous function very easily. Here is an example of how you can easily make it happen in the code. (function() { console.log('This function is being executed immediately right after its creation');})(); Output So in the above example, the function is getting executed right after its creation. The syntax is simple: you can simply declare the anonymous function and make it execute by just calling it using the parenthesis at the end of the function. Here is how you can do this below: let obj = {'name': 'John Doe','age': 22,'address': 'xyz'};(function() { console.log('My name is ', obj.name, ' and my age is', obj.age, ' and I live in ', obj.address);})(obj); Output You can simply pass the parameters inside the immediate execution of the anonymous function as we have seen in the above example.

 Arrowed Anonymous function

The arrowed anonymous function is similar to the non-arrowed anonymous function, it’s the short syntax of the function and can be easily implemented in the program. Arrow functions are the modern ES6 features actually, which allows you to write the code fast and easier, it is basically a shorthand approach to declare and use the functions. Here is an example of the shorthand anonymous function. let AnonymousFunc = function () { console.log('This is an Anonymous function');}; You can write the above function as a shorthand arrow function as below let AnonymousFunc = () => console.log('Short hand Arrowed Anonymous function'); AnonymousFunc(); Here is the output

 How to reuse the Anonymous Function

JavaScript’s anonymous functions can be reused later on. You can make them reusable by assigning them to a variable and then calling them wherever you want. Let’s take a look at the example below to make a clear understanding of how we can easily use anonymous functions in the future. let AnonymousFunc = function () { console.log('This is an anonymous function');}; AnonymousFunc(); Output: So if you take a look at the above example, you will find out that there’s no name between the function keyword and parentheses which is making it completely Anonymous but why we are assigning this anonymous function to an AnonymousFunc variable is because we want this function to be callable later.

 Conclusion

An anonymous function is a function with no name which can be used once they’re created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function. In this article, we have discussed how we can create an anonymous function and store them for future usage as well.

JavaScript – Coding Standards and Conventions

JavaScript is a web programming language that is used to develop web applications and web pages and makes the web application interactive. Like any other programming language, JavaScript has some coding standards and conventions. Creating large programs and software code becomes too messy and unmaintainable if coding standards and conventions of the programming language are not followed. Coding standards are sets of rules and principles that define a programming language’s programming style, techniques, and methods. Coding standards are a necessity as, without them, every employee in an organization will develop a program based on their coding style, hence creating confusion and making debugging too hectic. Coding standards and conventions hence come into play which improves the code readability, quality, and making debugging easy. In this post, we will go through the coding standards and conventions of JavaScript, so, let’s get started.

 Indentation and function

JavaScript coding conventions say that use two spaces to indent JavaScript code, and never use trailing whitespaces. For functions, use camelCase and to define a function use the keyword function: function myFunc(){ var x=0;}

 Variable Names

The name of a variable must begin with a letter and camelCase is used to initialize variables or functions which means the first letter should be a small letter and if another word is added after the first word then the first letter of that word should be capitalized. var fullName = "Jackie Chan";

 Spaces, all brackets

Always leave spaces between operators such as (= + – * /) and commas: let name = fName + lName;const myArray = ["cat", "mouse", "dog"];

 Object guidelines

For using objects, the coding standards include the following points: The starting bracket should be placed on the same line as the object name. Between an object’s property and its value is a colon and a space. String values are covered with double quotations. Numeric values are simply written and quotes are not used. A comma is used after every property value pair except the last one After the object closing bracket, add a semicolon. Objects that have fewer properties can be compressed and written on the same line by having spaces between properties. var person= { firstName: "Jackie", lastName: "Chan",};//can also be written in compress form var person = {firstName:"Jackie", lastName:"Chan"};

 Statement Guidelines

A simple statement like initializing a variable that ends on a single line should have a semicolon at the end of the line: var name = "Jackie Chan"; For a compound sentence, leave a space and place an opening bracket after which then fill in the rest of the sentences in that opening bracket. Once all the statements are finished, put a closing bracket. It should be noted that in a compound sentence we don’t put a semicolon at the end of it: for (i = 0; i < 3; i++) { a *= i;}

 Line Length

Standard coding and conventions say that lines length greater than 80 should be written on another line by breaking the original line so that the code becomes more readable: document.getElementById("example").innerHTML ="Example!";

 File Extensions

Javascript coding standards and conventions say that the HTML file should have a .html extension, the CSS file should have a .css extension and the Javascript file should have a .js extension.

Loops and Conditions

After a control statement’s identification, and after every comma use whitespace. The conditional statements coding conventions and standards code is given below: if (condition1 || condition2) {// some statements}else if (condition3 && condition4) {// some other statements}else {// default statements} For loop follow the below code: for (let i = 0; i < 5; i++) { x += i;}

Comments

Block comments are avoided according to coding standards and conventions and line comments are used. Comments are put in the left margin and // are put in the start. // an example var name = "Jackie";

 Conclusion

Coding standards and conventions are a set of rules that define a programming language style, techniques, and methods and are followed to avoid confusion and enhance readability and debugging. The development cost is reduced and team integration becomes very easy when coding standards and conventions are followed. In this post, we discussed JavaScript coding standards and conventions with examples.

Memory Management – Garbage collection

JavaScript doesn’t provide much in the way of memory management or garbage collection because we cannot directly use operations related to memory but for knowledge purposes, it is good to know how it operates. In C language, developers manually allocate or deallocate memory with malloc(), calloc(), realloc() and free() methods. JavaScript values work as the values are allocated after the creation of objects, or strings; and are automatically freed when the process is completed, so this whole process is known as Garbage Collection. The Memory Management Lifecycle is based on 3 steps.
    Allocation of Memory Utilization of Memory Releasing Memory

 Memory allocation

After introducing the variable, JavaScript allocates memory for its assigned variables. At the point when the memory is not useful any longer, then memory will be released. When memory is released then several issues including leakage of memory arise. The most difficult task is to discover the memory which is not useful and subsequently deallocate the memory efficiently with the help of a garbage collector. The garbage collector tracks the memory which is not required, but the most difficult task is to track unused memory. If you declare values to variables then memory allocation is assigned automatically. In these examples, variable1 allocated memory for a number whereas the string is allocated in the memory of variable2 as shown below. var variable1 = 100; var variable2 = "Memory Allocation"; If you want to assign memory for numerous objects then use the following code. var variable3 = { variable4: 5, variable5: 'Test'} Array allocated in the memory of variable6 as shown below. var variable6 = [1,2,3,4,5] You can also allocate memory for distinct methods. Here is the code to allocate memory for a method. function function_name(x) {return x + 20;}

 Garbage collector

The process of memory allocating and releasing the memory when not required is known as garbage collection. Algorithms are used to find out which memory is irrelevant for the tasks. This section explicitly deals with the main algorithms used in garbage collection and their limitations.

 Reference counting garbage collection algorithm

Reference counting garbage collection algorithms are viewed as the great fundamental sort of garbage collection. This algorithm not only decides if any resource is significant or not, it also filters the memory to decide whether an item has some other instances referring to it. An instance that has null references is accounted for as garbage.

 Mark & sweep algorithm

A garbage collector helps to free up memory whenever an instance is inaccessible, instead of a zero referring to an object. Initially, the garbage collector searches all global or root instances along with their object references. Through this algorithm, the collector will distinguish between the reachable and inaccessible instances. Subsequently, inaccessible instances will be collected automatically by the garbage collector.

 Conclusion

JavaScript efficiently allocates memory and subsequently, the garbage collector helps to detect this allocated memory and reclaim it whenever memory is not useful. We learned how we can manage memory and collect garbage in this article. We need to take care that we have to implement software programs that cannot cause circular referring to variables. We have to make sure that we cannot program anything which will throw variables out of the garbage cycle.

How to use the modulo operator (%)?

JavaScript is a web-based programming language that makes our web pages and web applications dynamic by giving them the ability to think and act. Like any other programming language JavaScript also offers operands and operators. Operators are symbols that instruct our system to perform an arithmetic task like addition, subtraction, and multiplication. Operands are the values that the operator performs actions on. One example of an operator is the modulo operator.

 What is a modulo operator?

A modulo operator also referred to as remainder or modulus operator is the remainder that is returned when some operand is divided with another operand. The Syntax for the modulo operator is: A % B We will read as A mod B where A and B are operands and the remainder that will be returned from the above operation will take the sign of the dividend.

 Example:

Let us go through the below example where we will console log the result of the modulo operation: console.log(15 % 5); //0 console.log(17 % 5); //2 console.log(-17 % 5); //-2 Let us now explore other areas where we can apply the modulo operators so we can get a grip on how to use the modulo operator.

 Testing number is divisible by another number

Let us check whether a number is divisible by another number or not with the help of the modulo operator: var num=4; console.log(num % 4 == 0 );// true as num is divisible by 4 console.log(num % 3 == 0 );// false as num is not divisible by 3 We initiated a variable with the name of num and gave it the value of 4. After which, we console log some operations to test whether num is divisible by 4 or not.

 Checking Even and Odd number

Another advantage we can take from the modulo operator is to check whether a number is odd or not using the modulo operator: var num=4; console.log(num % 2 == 0 );// true as num is even number console.log(num % 2 != 0); // false as num is odd number A variable num is initiated first and then with the help of the modulo operator we check when the num is divided with 2, the result is 0(num is even) or not(num is odd).

 Getting the Fractional part of a number

Suppose you encounter the problem of finding the fractional part of a number i-e the number after the decimal point for example if you have a number 2.25 then extract the 0.25 from that number and return it. To achieve this task, we will take help from the modulo operator: functiongetFractional(num) {return num % 1;} console.log(getFractional(2.25)); // 0.25

 Conclusion

Like any other programming language, JavaScript offers us operators and operands. For example, In num1 + num2, num1 and num2 are operands, and math + is the operator. JavaScript offers us the modulo operator as well which returns the remainder of two operands. In this post, we saw what the modulo operator is and how to use the modulo operator with the help of solving problems like finding even and odd numbers and extracting the fractional part of a number.

How to take input with Radio Buttons

JavaScript is a programming language that gives our web applications and web pages the ability to think and act by making them interactive. Javascript offers us radio buttons that are used to set up a group of related options with just one radio button chosen at a time. Radio buttons are mostly used in forms and used with the <input> element of HTML. Radio buttons come in very handy when the developer wants the user to select just one option from the given multiple options. For example, your web application accepts either email or phone number and you want the user to select one and not both. Radio buttons come in handy in achieving this task. First, we will define radio buttons in HTML and then go towards JavaScript so that we can take input with radio buttons.

 HTML

<p>Choose your preferred option</p><input type="radio" name="contact" value="email" /><label for="email">Email</label><input type="radio" name="contact" value="phone" /><label for="phone">Phone</label> In the above HTML code, we used two radio buttons and gave the name of the contact. It is necessary to give the same name to the same group of radio buttons so that only one can be selected at one time. We also used labels to label our input radio buttons. We will see the following output in our browser when we run the above code: We can also see that only one radio button can be selected at any given time. Before going towards the JavaScript part, let us initiate a submit in HTML as well so that we can later listen for events on this button. <body> <p>Choose your preferred option</p> <input type="radio" name="contact" value="email"/> <label for="email">Email</label> <input type="radio" name="contact" value="phone"/> <label for="phone">Phone</label> <button onclick="handleClick()">Submit</button> <script src="code.js"></script> </body> We initiated a button and gave it an onclick event so that when the user clicks on the submit button, the handleClick() function will start executing. In the end, we referenced our JavaScript filename with the help of script tag and using the src attribute passed the file name which is code.js.

 JavaScript

Now that we have defined two radio buttons in HTML, let us take the next step towards getting input from the radio button hence it is necessary to first determine which radio button is active or selected. For this purpose, we will use querySelectorAll() which will select all the radio buttons with the name contact. functionhandleClick(){ constradioButtons= document.querySelectorAll('input[name="contact"]'); letselectedValue;for (constrbofradioButtons) {if (rb.checked) { selectedValue = rb.value;break; } }if(selectedValue){ alert(selectedValue); }else{ alert("Please Select an option"); }} In the above JavaScript, the handleClick() function is created at the start which is called from the HTML submit button. After this, using the querySelectorAll(”input[name=” contact”]”) we select all the radio buttons that have the name of the contact and save the reference of all the radio buttons in the variable radioButtons. After which, we created a loop that will iterate through every radio button and will check whether any radio button is checked or not which means the radio button is selected or not. If a radio button is selected then it will store the value of that radio button in the selectedValue variable. Once the loop ends, we unify the if/else statement which checks whether the variable selectedValue is empty or not. If it has some value then it will alert that value, otherwise an alert of Please Select an option will be shown to the user. We can see in the above output that when we didn’t select a radio button the alert showed us the message that Please Select an option. However, when we select the Email radio button, we see the value of email and when we select the Phone radio button then we see the value of the phone.

 Conclusion

To set up a group of related options, and selecting just one at one given time, radio buttons are used. Radio buttons are initiated with <input> elements of HTML and the checked property is used to see whether a radio button has been selected or not. Radio buttons come in very handy when there are multiple options available and the developer wants the user to select only one. In this post, we learn how to take input with Radio buttons.

How to downgrade or upgrade the node version?

Whenever you are building some node js application, you will have to work on some specific version as many organizations are using some specific version of node js for building the applications, hence you might always need to upgrade or downgrade your node version according to the requirements. In this article, we are going to discuss how you can simply upgrade or downgrade the node js version using some simple tricks and commands.

 What is Node?

Without the need for a web browser, Node.js runs JavaScript code. Node.js is quite popular due to its cross-platform nature since it can be used as Node.js on Windows or Node.js on Mac. As a result, Node packages may be utilized in the creation of mobile apps. In some situations, you may utilize Node.js for iOS programming or Android development. Since Nodejs has an active community of users, minor updates come out after every few weeks.

 What is NPM?

The npm is the default package manager for Node.js and is used to manage javascript packages and modules. npm register and the command line interface is being used.

 What is Yarn?

Yarn is also a package manager for npm and also works the same as npm, it can also be used to manage and control the node packages like installing modules and controlling the version etc.

 How to install Node?

To get started with Node.js, visit NodeJS official website and download the Node.js installer for Windows, macOS, or Linux. If you have a really particular deployment target, you may even obtain the source code and assemble it yourself.

 How to Downgrade or Upgrade Node.js

You may verify the node version using the node -v command in the terminal before doing any activity. Then you may update Node using one of the ways listed below. You may also pick a certain node version or degrade it. By supplying a version in the associated instructions, you can downgrade the node version.

 Update the node version using installers

Visit the official website of the Node and there you will find out the latest and a stable version of the node hence you can download it from there.

 Updating Node.js using npm

To use npm to update Node, you must first install the n module: Clean up the npm cache: npm cache clean -f Then you may install the most recent version of Node: n stable or To install, choose one of the following versions: n [version-number] – the version number might be anything from 614.9 to v8.1.2.

 Upgrading/Downgrading Node using nvm:

nvm is another useful tool that can help you to control the node version itself, you can use nvm commands to upgrade the node version quite easily. you can simply install the nvm package and that’s it from your side now you nvm is responsible for controlling your node version. Whenever you need to upgrade or downgrade a node version you can simply type a few commands given below and that’s it. Let’s take a look at how we can easily upgrade or downgrade the node version using nvm. use the below command to install the latest node version using nvm. $ nvm install node for installing a specific version of the node you can type the following command $ nvm install <version-number> Here the version-number is the version of the node which you will be installing particularly. for example $ nvm install 12.18.2 output Similarly you can downgrade your node version to the specific version you want by just typing the version number in the above described command and that’s it.

 Conclusion

Nodejs can be upgraded or downgraded using different methods some of them are by manually downloading the latest version of node from their official nodejs.org website and the second method is by using nvm which is really helpful in controlling the node version. you can simply type the above discussed command and install the specific versions of the node and latest version of the node as well.

How to split a string using the split() method?

Like any other, high-level programming language JavaScript offers us datatypes where we can store data, and one such data type is a string. A string is simply any textual content enclosed in double or single quotation marks for example “split method” is a string. To manipulate the string data type, there come some inbuilt methods(predefined functionalities) and one such example is the split() method.

 What is a split() method?

The split() method divides a specific string into an array of substrings without changing the original string and produces a list of substrings as an array taking two arguments; one is the splitter and the other is the limit. The splitter acts as the divider and tells the split() method where the specific string should be divided. The splitter can be a regular expression, a single character, or another string. If you don’t provide the splitter in the split() method then the specified original string will be returned. The limit argument tells the split() method what is the limit where you have to stop the substring process or to put it simply it specifies the number of splits. However, it should be kept in mind that if you don’t give the limit argument to the split method then an empty array will be returned. Syntax: myString.split(separator, limit); Where myString is the specified string and the separator is the splitter and the limit is the specified number of splits.

 Split a string using the split() method

Now that we know the split() method splits a specific string into substrings and returns a new array of the substring, let us go through a few examples where we will split a string using the split() method:

Example 1:

In this example, we will split our string into words in the following manner: var myStr = 'String into words'; var output = myStr.split(' '); console.log(output); In the above code, we initialize an array and then apply the split() method on the array. The separator in this case is a space(‘ ‘) which means whenever the split method will see a space, it will divide the string and return the word before the separator.

Example 2:

Let us modify the above example, and return only the first two words in the sentence hence we will use the limit=2 in this example: var myStr = 'String into words'; var output = myStr.split(' ',2); console.log(output);

Example 3:

Let us move one step forward and provide a regular expression as a separator. The code will be the same except that we will change the string and provide a separator as an array of regular expression in the argument of the split() method: var myStr = 'Hello! How are you? My name is Chris'; var output = myStr.split(/[!,?]/); console.log(output); As you can see, we provided an array of separators where we defined that if the split() method gets a ! or ? then divide the string. The output of the above code will be:

 Conclusion

JavaScript offers us primitive data types which are used for storing data and one such example is a string. The string is some text in double or single quotation marks and it has numerous inbuilt methods. One such method is the split() method that divides a specific string according to a separator into substrings and the substrings array is returned without changing the original string. In this post, we looked at what is a split() method and how to split a string using the split() method by giving three different examples and screenshots of the output.

How to create a link using javaScript?

Whenever you are developing a web application or website you will have to deal with URLs and links which are frequently used to navigate a user from one page to another, as there is no other way to navigate your users without links and URLs. Hence, you need to create them and put them in the exact places where you want to navigate the users.

 Why do you need to create links with JavaScript

HTML allows you to put links inside the anchor tag under the href attribute. However, while developing a JavaScript-based application where you have to handle everything programmatically, you need to create links dynamically and assign them to the href attribute of the HTML anchor tag. This is the major reason why you need JavaScript to create a link and this is what we are going to talk about in this article so let’s have a deep dive at how we can easily create a link using JavaScript.

 Approach to Create a link

To create a link programmatically, we first understand what exactly we need to do. First, we need to create an anchor tag using javaScript: <a></a> Create an anchor <a> tagFor creating an anchor, we can utilize the code provided below. Create an element(<a> tag) and assign it to the variable named “anchor” as we will need it later: let anchor = document.createElement('a'); After creating the anchor tag, we need to write some text inside the <a> tag as demonstrated below: <a>Linuxhint website<a/> Write text into the <a> tagFor writing some text inside the <a> tag, first create a text node and then append that text node as a child to the anchor tag. The code for writing text into the anchor tag will go like this: //create a text node and assign it to the "link" variable. let textNode = document.createTextNode("Linuxhint Website");// Append the textNode as a child to anchor. anchor.appendChild(textNode); At this stage, the text is appended into the anchor <a> tag. Now, we need to put the link in the href attribute of the anchor <a> tag as shown below. <a href="https://linuxhint.com/">Linuxhint Website<a/> Set the href attribute of <a> tagTo put the link in the href attribute of <a> tag, the following line of javaScript code will be used: anchor.href = "https://linuxhint.com/"; After setting the href attribute, the only thing left is to append the <a> tag where we want it to be put. Append the <a> tag to HTML bodyTo append the anchor tag to the body, use the following line of code. document.body.appendChild(anchor); Alright, you have learned all the procedure to create a link using javaScript. Let’s go through an example to demonstrate the results.

 Example

Let’s take a simple example where we will simply create a link and append it to the HTML body and will checkout the behavior of the link if it is working or not. HTMLFirst, we will create a button and at the click of that button the createLink() method will be called. <button onclick = "createLink()"> click here</button> JavaScriptAll the code for creating the link will be written inside the createLink() function and the whole JavaScript code will go like this: function createLink() { let anchor = document.createElement('a'); let link = document.createTextNode("Linuxhint Website"); anchor.appendChild(link); anchor.href = "https://linuxhint.com/"; document.body.appendChild(anchor);} Once everything is in order and ready to be executed, let’s verify this and run the code. Output Click the button and see if it is actually creating the link for us or not. Here in the above screen, you can see that after clicking the button, the link was created successfully and displayed on our webpage. This link has given up with the address of linuxhint.com which means if you click on it you will be directed to linuxhint.com. Remember that we have appended the link in our JavaScript code that’s why it is appearing below everything. So now if you want to prepend the link to the top of some HTML element or at the top of the page then simply prepend the anchor tag instead of appending it to the body to achieve this objective. Prepend the <a> tagThe only change that we need is to use “document.body.prepend” instead of “document.body.append” to prepend the anchor tag to the top of the page above every element. document.body.prepend(anchor); Output As you can see above, the link was prepended on top of every HTML element and is clickable with the address attached to it.

 Conclusion

Link can easily be created through JavaScript by first creating an <a> tag using createElement() method and later the link can be attached to the href attribute of <a> tag. This post has provided the complete function for creating a link totally through JavaScript without touching the HTML. Moreover, we have discussed how to append or prepend the anchor tag “<a>” to the body using detailed examples.

C++ vs JavaScript – Should I learn C++ or JavaScript

C++ and JavaScript are the most evolving programming languages and are used widely by software developers. C++ and JavaScript are well-known languages to learn as they contain several applications that can be used to develop a wide variety of applications. In this article, we demonstrate the features of JavaScript and C++ then we compare both languages in-depth to completely grasp their benefits. Subsequently, we briefly discuss how they pile up against each other.

 JavaScript

JavaScript was developed in 1995 by Netscape. JavaScript is an emerging interpretation, the high-level language used to create websites. Web developers use JavaScript to make the content of the website interactive. JavaScript is capable of loading web pages dynamically. So, whenever a web page is loaded, JavaScript efficiently turns the code of the virtual machine at its execution time. HTML and CSS are the main web technologies that are used for web page layout and for interactivity JavaScript is used with them. These three technologies are known as the default languages of websites. Facebook, Google, and many more applications use JavaScript in their web pages. Almost all browsers have built-in features in order to handle JavaScript. Few features of JavaScript is enlisted below: Used to build interactive websites Easy to learn Interpreted language Typed dynamically

 C++

C++ is the most popular programming language not only used to create websites but also used to build video games, space probes, etc. Classes can be used in C++ programming language. C++ generally follows the concept of object-oriented and is one of the most efficiently compiled languages in terms of performance. The best thing about the C++ programming language is that you can easily write compilers for different languages. C++ is known as the backbone of other languages as it provides shine to them. Following are the features of C++: Based on object-oriented programming language Compiled programming language A bit difficult to learn Typed statically

 C++ vs JavaScript

C++ and JavaScript are not as easy to compare as you think. Both are comparatively different languages but we still try to compare them with each other.

 C++ vs JavaScript in terms of Speed/Reliability

If we talk about speed and readability then we say that JavaScript is a more high-level scripting language as compared to C++. JavaScript is capable of doing the same thing in one line of code as C++. Hence, the code of JavaScript is less than C++. C++ has a considerable amount of code but it is not generally guaranteed that you will always find integration which you are searching for whereas JavaScript provides a cushion around it. C++ is additionally statically composed whereas JavaScript is dynamically composed. This implies that you need to declare variables during developing an application., you don’t need to stress a lot whether something is a number or a string. However, it means that JavaScript can type numerous lines of code somewhat speedier. As discussed above, C++ is a compiled language which implies that you will need to compile your code before its execution. It can take a couple of moments to 60 minutes, contingent upon the complexity of your code. What’s more, you need to do this each time you roll out an improvement either for bug testing or troubleshooting. On the other hand, JavaScript does not require compilation as it executes efficiently whenever you press the run button. Generally, this isn’t really a reasonable correlation, as JavaScript code is more limited than the huge C++ projects that take such a long time to compile; still, it’s as yet important.

 C++ vs JavaScript in terms of Syntax

If we talk about the syntax of C++ and JavaScript then you can say that JavaScript is a scripting language intended to help styles of basic programming or functional programming. It also assists event-driven. Since JavaScript is working with dates, texts, arrays as well as regular expressions so it likewise contains all the APIs. C++ is inflexible; it considers significantly less space. It gives you an error if you missed inserting a semicolon at the end of each statement. Hence, you need to follow the basic syntax of C++ while writing code.

 C++ vs JavaScript in terms of Performance

Performance is defined as how rapidly compiled programs can execute. If we talk about the execution of a program then we say that the compile time of C++ is multiple times faster as compared to JavaScript. On the other hand, JavaScript is simpler to type, however, more effort is required to interpret code at runtime. JavaScript is a scripting language that can be typed more quickly but it takes time to execute the code. While talking about performance then the most essential point that must be kept in mind is that JavaScript is not intended for substantial computations and calculations just like C++. Therefore, the slower performance of JavaScript is not a big deal as compared to C++.

 Community of C++ and JavaScript

Both JavaScript and C++ have been profoundly used for more than 20 years but JavaScript evolved later than the C++ programming language. They both have communities worldwide. Both of them have tremendous libraries and code models. Nonetheless, JavaScript has less application than C++, so it has a lesser pool of individuals behind it.

 Conclusion

JavaScript and C++ are well-known programming languages; both have their own benefits and downsides. The major misunderstanding is that you need some information about Java in order to learn JavaScript. It is to clarify that all of the above two languages are different from each other. In this quick article, we’ve learned the main differences between C++ and JavaScript. In the initial learning stages going with C++ is better, keeping in mind that JavaScript is much easier among other programming languages. It all depends upon the usage of the user, whether one wants to work over web pages then go for JavaScript, and if anyone wants to develop applications running on the client’s system then C++ shall be used.

How to convert Celsius to Fahrenheit

According to the international system of units (SI), Celsius and Fahrenheit are both derived scales that are used in replacement to kelvin. Fahrenheit was invented by German physicist Daniel Gabriel Fahrenheit while Celsius was invented by Swedish astronomer Anders Celsius. Both of these measuring scales are the world’s most frequently used scales when it comes to measuring temperature. Water freezes at 0℃ on Celsius, while it boils at 100℃. Fahrenheit has a freezing point of water at 32 and a boiling point of 212℉.

 Conversion of Celsius to Fahrenheit Scale

With the following equation, we may convert from Celsius to Fahrenheit: F = (9*C + 160) / 5 The temperature in Celsius is C, and the temperature in Fahrenheit is F.

 Conversion of Fahrenheit to Celsius Scale

Similarly, using the equation below, we may convert from Fahrenheit to Celsius: C = 5/9 (F-32) The temperature in Celsius is C, and the temperature in Fahrenheit is F. In this write-up, we will learn how we can convert our temperature from Celsius to Fahrenheit. Let’s jump into the implementation part:

 Celsius to Fahrenheit Example

In this example, we will see how we can implement the algorithm in a javascript code. let celsius = 32 let fahrenheit = 0const convertTemp = (TempInCelsius) => { fahrenheit = (9 * TempInCelsius + 160)/5 console.log(fahrenheit)} convertTemp(celsius) The above code takes a Celsius temperature and converts it into Fahrenheit. In this code, celsius is a variable that holds the value in the Celsius scale. Fahrenheit is also a variable that will store the result in Fahrenheit. Initially, Fahrenheit is set to 0 while it gets the calculated value when the convertTemp() is called. The convertTemp() function takes a parameter which is of course the celsius value and then computes it into Fahrenheit and stores it into the Fahrenheit variable. This function also logs the value in the output terminal as well. Here is the output: E:\nodeWorkspace>node basic.js89.6 Let’s implement the above code in HTML which will dynamically calculate the celsius value into Fahrenheit: HTML Code: <div class="container"> <div class="row my-5 py-5"> <div class="col-4 offset-4"> <div class="form-group"> <label for=">Enter the temperature below</label> <input type="text" id="temp" class="form-control"> </div> <input type="submit" id="submit" class="btn btn-success"> </div></div><div class="row my-3 py-3"> <div class="col-4 offset-4"> <div class="form-group"> <label for=">Temperature in Fahrenheit</label> <input type="text" id="Faht" class="form-control" readonly> </div> </div></div> JavaScript Code: <script> let Fahrenheit = document.getElementById('Faht') let submit = document.getElementById('submit') submit.addEventListener('click', (e)=>{ let Celsius = document.getElementById('temp').value e.preventDefault() result(Celsius) }) const result = (cel) =>{ Fahrenheit.value = (9 * cel + 160 ) / 5 }</script> In the above HTML code, we have used bootstrap to give styles to the elements to make them look a little better than the default ones. There is an input field temp which takes in the integer value and another input field with the id of Faht which is a read-only field and can only output the calculated result of the celsius value. In Javascript code, there is an onClick event listener on submit button which upon clicking, triggers the result() function and sets the value to the read-only input field, and displays it on the browser. Let’s see the output on the browser: After entering the values we will see the following results:

 Conclusion

For converting the temperature from Celsius to Fahrenheit, you can use the formulae F = (9*C + 160) /5 in which F is the temperature in Fahrenheit and C is the temperature in Celsius. You are only required to put this formula in the JavaScript and provide the temperature in the required scale and the program will convert it to the desired Scale which in our case is Fahrenheit. Well, we learned how to convert Cecsius to Fahrenheit and vice versa.

How to implement a Linked List data structure?

Javascript is a web programming language that is used to make our web pages and web applications dynamic and interactive by giving them the ability to think and act. Like any other programming language, JavaScript offers us arrays which are a collection of different elements stored in a single variable. The limitation of an array is that it is stored consecutively at a particular memory in our system hence to solve this problem we use a Linked List.

 Linked List

The Linked Lists are like arrays except that in a linked list the items aren’t saved in a specific memory location or index and every element is a separate independent object that is connected to the next element by having a pointer or link to that element. Every linked list contains a head(first node), length(size of the linked list), and a tail(last node) property, and each element in a linked list is called a node and every node has a value stored in it and the link to the next node. If the current node is the tail then the link will be null that is not pointing to any other node. The linked list doesn’t contain indexes unlike arrays that have indexes e.g 0,1,2.. and so on. Linked Lists can be demonstrated as follows: // Linked Listconst LinkedList = { // every node has a value and pointer // first pointer is the header head: { value: 6 next: { value: 10 next: { value: 12 next: { value: 3 next: null } } } } }}; Linked List advantage is that elements(nodes) are easily added and removed from the linked list without adjusting the whole linked list. The disadvantage of a linked list is that it needs more memory for storage as now we have an extra pointer that we are storing along with the value of the element. Linked Lists are of three types which are described below: The singly linked list has only one pointer pointing to the node next to it. The doubly linked is based on two-pointers in which the first one points to the node that is behind it and the second one points to the node next to it. The circular linked list whose tail contains a pointer to the head and hence forms a cycle.

 Linked List Implementation

Let us first create a node that has two properties a value and a pointer for which we will create a class with the name of ListNode that has these two properties: class ListNode { constructor(value) { this.value = value this.next = null }} Now that we know how to create a node let us create a linked list where the default value of the head will be null: class LinkedList { constructor(head = null) { this.head = head }} Let us now initialize the linked list with two nodes and add a pointer from the head or node 1 to the second node: var node1 = new ListNode(3);var node2 = new ListNode(4); node1.next = node2; The next step is to initialize the linked list with node1 in the following manner: var list = new LinkedList(node1); The whole code is given below with console logging the node2 value: // creating nodeclass ListNode { constructor(value) { // Constructor initializing value and the next pointer this.value = value this.next = null }}class LinkedList { // Linked List Constructor constructor(head = null) { this.head = head }}// initializing created nodesvar node1 = new ListNode(3);var node2 = new ListNode(4); node1.next = node2;// initializing linked listvar list = new LinkedList(node1);// showing output of the second node console.log(list.head.next.value) // 4

 Linked List Methods

Now that we are done with implementing the linked list, let us play or manipulate the linked list by implementing more methods to make use of the linked lists(helper methods): The first helper method we will define is the size() method in the class LinkedList which will return the length of the linked list: size=()=> { let count = 0; let node = this.head; // loop to iterate over linked list while (node) { count++; node = node.next } return count;} In this code first, we are declaring a dummy variable count storing 0 in it and then storing the pointer of the head in the node variable. Then we declared a loop that will iterate over the linked list and increment the count variable. The next helper method will be the getFirst() method where the head pointer will be returned: getFirst=()=> { return this.head.value;} We can also get the last node of the linked list in the following manner: getLast=()=> { let lastNode = this.head; if (lastNode) { while (lastNode.next) { lastNode = lastNode.next } } return lastNode.value} The whole code is now given below with showing the output of the second node value, size of linked list, first node value, and the last node value in the same order: // creating nodeclass ListNode { constructor(value) { this.value = value this.next = null }}// creating Linked Listclass LinkedList { constructor(head = null) { this.head = head } size=()=> { let count = 0; let node = this.head; // loop to iterate over linked list while (node) { count++; node = node.next } return count; } getFirst=()=> { return this.head.value; } getLast=()=> { let lastNode = this.head; if (lastNode) { while (lastNode.next) { lastNode = lastNode.next } } return lastNode.value }}// initializing created nodesvar node1 = new ListNode(3);var node2 = new ListNode(4); node1.next = node2;// initializing linked listvar list = new LinkedList(node1);// showing output of the second node console.log("Second node value: ",list.head.next.value) // 4// showing size of the linked list console.log("Size of Linked list: ",list.size());// showing first node value console.log("First node value: ",list.getFirst());// showing last node value console.log("Last node value: ",list.getLast());

 Conclusion

After arrays, a linked list is the second most used data structure in any programming language. A linked list is like an array that stores a collection of different elements with the difference being that every element(node) of a linked list is an object containing a value of the element and a pointer pointing to the next node hence linking every element and the second difference is that the items aren’t saved in a specific memory location in a linked list. In this post, we saw what linked lists are, the advantages and disadvantages of linked lists, the types of linked lists, and how to implement linked list data structure.

What is JSON – Tutorials for beginners

JavaScript Object Notation commonly known as JSON is a data transmitting format that is completely independent of programming languages and is used for structured data. JSON allows machines to easily deconstruct the structure of the data to utilize them in all the other languages. JSON is a subset of JavaScript’s Objects Notation, but it does not only rely on JavaScript. It can be used in almost every language. It is an alternative to the older data-interchange format like XML, but being lightweight, easy human readability, and independence from any programming language makes it more unique. JSON has replaced XML and is most frequently used in data-interchange format these days. It has the same properties as the JavaScript Object (as it is a subset of JS Object’s notation) but is used for generic data structures in modern world applications.

 JSON usage

JSON has the ability to transfer the data from computers to computers, databases to databases, and programs to programs. It is commonly used to transmit serialized data over the network connections Because of being an independent data format, it can be utilized with all the other languages easily Most frequently used data format in modern world apps Can be useful to transit data from web apps to the server

 Properties of JSON

Following are the properties of the JSON which are mainly focused on in this article. It is a text-based data structure. It is an extension of JavaScript Object Notation. It is easy to understand for the end-user, programmer, and the machine as it is text-based and lightweight. JSON is completely independent of a programming language, but it includes many conventions that are repeatedly used in other languages like, C, C#, C++, JavaScript, Python, and Perl Until now we have gone through the introduction, Usage, and properties of JSON. JSON mainly came for exchanging data across the systems with a common readability stream that was easily understandable by the system and the humans as well. So, in early 2000, Douglas Crockford specified JSON after recognizing the necessity for a real-time communication protocol. Previously, JSON was considered a subclass of JavaScript and was widely utilized with it. However, JSON serialized and parsed code is accessible in practically every major programming language.

 Data Types in JSON

JSON has the following major data types. Strings Numbers Booleans Arrays Objects Strings will always have double quotes around them, remember that JSON will not be able to identify the string if it has single quotes around it and as a result, it will leave an exception. Do not write like this: {name: John Doe} Or this: {‘name’ : ‘John Doe’} Right Method: {“name”: “John Doe”}

 Syntax of JSON

You have a basic understanding of JSON now. The method for creating a basic JSON file is explained below. JSON consists of a set of name-value pairings as well as an ordered list of values. JSON is a universal data form that is supported by nearly every computer language available today. Having an interchangeable data type that can be used in multiple languages makes a programmer’s job much easier. In JSON, key-value pairs will be enclosed inside curly braces { }, if not, there will be an exception generated by the compiler. The example of a basic .json file is given below. { "name": "John Doe", "Age": 28, "gender": "male", "Designation" : "Manager"}

 What is JSON Object

JSON Object is a set that contains keys against specific values without following any order. In JSON objects, values can be of different data types like Strings, Arrays, Booleans, Objects, and Numbers. So, the first thing we’ll need to make a JSON file is an attribute. I have created a “Person” object. Now we have to define the object’s properties. Assume a Person has a “Name,” Age”, “Gender “. These properties are denoted by ‘’Keys’’ in a JSON object. Let’s take an example of a basic JSON object: Person = { "id": 001, "name": "John Doe", "age": 28, "gender": "male"} In the above example, we have created a Person object which contains the information of a person like his name, age, and gender. As we have discussed above, we use a key-value pair in a JSON, hence we need to put a key against each value to form an object in JSON.

 Creating JSON Arrays

Arrays in JSON are the same as those in any programming language. The array is identical to the term set and has a sequenced collection of data present in it. We use the comma ‘,’ between the values residing inside the array to make them individual. If you’re going to use an array in JSON, these are a few basic principles to follow. Let’s take the example of JSON arrays. ["Fruits", "Vegetables", "Meats"] Just like other languages, JSON arrays are also formed in an exact way. The above array contains the string values but you can add whatever type of data you want inside the arrays. Remember, unlike objects, there are no keys against the values of the array. Let’s take another example of it. myArray = ["fruits", "Vegetables", "Meats"]; Here is how you can get the values you want from an array. myArray[0] So basically this is going to retrieve the information that is placed on the 0th index of the myArray. Similarly, you can easily get the value by just defining the index of that value using the above example.

 Complex JSON Objects

The complex JSON object contains complex object structures, which means it will have complex values against keys. Unlike the above examples, complex JSON objects contain objects inside objects and arrays inside the object which makes it a bit difficult to understand but if you got the concept of objects and arrays till now, this will lead you to understand the complex JSON objects easily. Let’s take an example of it: { "Book": { "Title": "Parsing Techniques", "Authors": [ "Dick Grune", "Ceriel J.H. Jacobs" ] }} Now in the above example, you can see that there is an object against the Book key which lies inside an Object. Hence this is the way to store the complex structures of JSON objects. Let’s take another example of it. { "Book": { "Title": "Parsing Techniques", "Authors": [ {"name":"Dick Grune", "university": "Vrije}, {"name":"Ceriel J.H. Jacobs", "university": "Vrije"} ] } } Now in this example, you can see that the Book key has an object as its value, and again that object has another key author which has an array against it as its value so this is what the complex JSON structure will look like.

 Conclusion

JSON is the most popular and the most commonly used data interchange format. It is a text-based structured data format, one of the biggest perks of JSON is the readability for humans and efficient usability for machines. We may make a simple JSON by assigning key-value pairs directly, or we can utilize arrays to assign numerous values to a single key. This enables the user to send data in a more complicated structure using the JSON format.

Array Every() Method

JavaScript every() method is a built-in array method that returns a Boolean result indicating if every element in an array meets a set of conditions. In other words, every() method checks whether your array passes a certain test or not and returns boolean true or false depending on the result of the test. Suppose you have just one element in your whole array that doesn’t meet the specified condition then every method will short circuit the loop and will break out of every method returning false. If it gets the false value in the middle then every method won’t check for other elements and break out of the loop, hence giving us a performance boost. It should be noted that every() method does not run for an empty array and it doesn’t change the original array. Also, as mentioned earlier, every method is an array method hence every method should be invoked only through an array object.

 Syntax

myArr.every(callback(currentValue,index,arr),thisArg) every() method takes some parameters which include a call-back function. The callback is a method or function that is supplied as a parameter to another method and begins execution only when the other function is completely executed. Callback functions ensure that the function will not execute unless some task or function has not finished executing. This call-back function runs for every element in the array. The callback function in this case also takes three parameters which are mentioned below: The currentValue is a necessary parameter and it indicates the value of the current element. The index is an optional parameter and indicates the index of the current element in the array The arr is also optional and refers to the array object to which the current element belongs. The every() method also takes another parameter which is the thisArg and is optional. The thisArg refers to the value which is passed so that it can be used as this value when the callback function is executed.

 Example

var numbers=[1,2,3,4,5,6];function check(currentValue) { return currentValue5} alert(numbers.every(check)); In the above example, first, we initiated an array with numbers ranging from 1 to 6. Then a function check is initiated which checks a value and returns true or false on the basis that the value should be smaller than 5. In the end, we initiated every() method on the numbers array and passed the callback function check. Now even if one element doesn’t meet the required check that its element value should be less than 5, it will return false. Hence, the first four elements are fine and are less than 5 but when it reaches the value 5, it will short circuit and will stop looking further. We will see false in the output:

 Example 2:

var numbers=[1,2,3,4,5,6];function check(element, index, array) { return element>0; //returns true as all elements are >0} alert(numbers.every(check)); We changed the example 1 code a little bit and modified it by providing the condition that the currentValue or every() element of the array should be a positive number, that is it should be greater than 0. We will see true now in the output:

 Browser Compatibility

The every() method is supported by almost every major browser and some of them are listed below:
BrowserGoogle ChromeMicrosoft EdgeSafariMozilla FirefoxOpera
Supportsyes>=9.0yes>=1.5yes

 Conclusion

The every() method is a JavaScript array method that is used to check for a certain condition on the array elements. It returns a boolean value, that is, if it passes the test for every array element then true is returned, otherwise false is returned. Once it gets an element that doesn’t pass the specified test, then it breaks every() method and returns false without checking the remaining elements. every() method is better than the for loop as every() method gives a cleaner code and hence enhances the readability and debugging of the code. In this post, we studied the array every() method.

What is debouncing?

Have you ever clicked on a button of a webpage and feel like it is taking a little too much time to load content. Similarly, while typing in the search bar the search takes a short delay to show the results. Even if you never felt it, let me tell you that developers used the function debounce to achieve this delay and this delay is very handy when it comes to stopping unnecessary requests to the server. For example, if you have set a function on window resize and now imagine calling the function continuously while we resize our window. Is it an efficient way of doing so? Of course not because calling that specific function continuously is unnecessary and hence it would affect the performance. In this post, we will talk about what is debouncing and its implementation with some examples.

 What is debouncing?

The simplest definition of debouncing would be that it is a programming technique meant to restrict the calling of a time-consuming (more computations) function frequently or only trigger a function when needed. Suppose, you are a developer and you are creating a search bar. You would want to show suggestions only once the user finishes typing meaning not on every single keystroke. Hence, using debouncing, one can improve their web page’s performance. How does debouncing work? Well, if I put it in simple words, then debouncing works by putting up a “wait” timer before the execution of a specific chunk of code. And if, due to some situation, the same process is re-executed. Then, rather than forming a queue of two same events, we stop the old process and only focus on the execution of the recent one. This also saves us from a “bottle-neck” situation. For those who are not familiar with the “bottleneck”, it’s a state that occurs when you are trying to push out more stuff on the screen than the processing power of the server

 Debouncing Implementation

We can implement debounce using the steps given below: Create a delay timer inside the function and set it to 0 Reset the timer if the specified function is invoked again Call the debounce function only when timeout.

 HTML coding part

The first step in implementing debounce will require an HTML element on which we will assign the click event. First, create a button element in HTML: <!DOCTYPE html><html lang="en"><head> <title>Debouncing</title></head><body> <button id="myBtn">Click Me</button> <script src="code.js"></script></body></html> The script tag is used to reference the file where we will write our JavaScript code that is code.js. We have also used the id attribute that we will use to reference the button element of HTML. Now that we are done with the HTML coding part, let us implement the debounce function.

 JavaScript coding part

The function for implementing the debounce technique would go like this: // get reference of the buttonvar myBtn = document.getElementById("myBtn");// debounce function definedconst debounce = (myFunc, delayTime) =>{ let debounceTimer; return function() { const context = this; const args = arguments; clearTimeout(debounceTimer); debounceTimer = setTimeout(() =>myFunc.apply(context, args), delayTime); }}// add an event listener to the button myBtn.addEventListener('click', debounce(function() { // alert will be seen after two seconds of time out alert("Hello World after 2 seconds");}, 2000)); In the above code, first, we get the reference of the button specified in HTML and add a click event on this button. Every button click would invoke the debounce function. In the debounce function, we are taking two arguments, the first is the function and the second is the delay time or the time out time. Then we initialized the debounceTimer which will track the delay period. When a user clicks the button once, the debounce function will be called after the delay. So, if the user clicks the button and then again clicks the button before the end of the delay then the timer resets, and the initial delay will be cleared. All this functionality is achieved by the function clearTimeout(). Let us see the output: We can see that when we are clicking the button, repeatedly we don’t see any output. However, when we clicked the button last time and left it, we saw the alert message after two seconds. Hence, we can conclude that every click calls the debounce function and resets the timer delaying the call.

 Conclusion

Debouncing is a programming technique used by developers to limit the number of calls to an event or only trigger a function when needed or for only one use case. The debouncing technique is applied in a time-consuming function that has a lot of computations so we avoid the unnecessary calling of that function. To be specific, debouncing can be applied in search bars, suggestive text bars, content loading web pages e.g Facebook, Instagram, and so on. In this post, we discussed what debouncing is and had a look at its working and implementation.

How to compare two arrays

To compare two variables we use the equality operator which is of two types. The first is the double equals “==” that checks two operands values and the second is the triple equals “===” which checks the value as well as the data type of the operands. However, we cannot use the equality operator for comparing the arrays. The reason behind this is that JavaScript array is an object type and objects are compared based on the references of the variables and not on the values. const array1 = [1, 2, 3];const array2 = [1, 2, 3]; console.log(array1 === array2); // false console.log(array1 == array2); // false In the above code, we have initialized two arrays that are the same. However, in the output we will see false: Hence to solve this problem, in this post, we will learn a couple of ways to compare two arrays.

 Method 1: toString()

The toString() method is an inbuilt method of JavaScript that converts any data type like integer to a string and then returns that integer number as a string. We can apply the toString() method on an array, which will convert the array into a string and then compare the string with the other string. const array1 = [1, 2, 3];const array2 = [1, 2, 3];const array3 = [4, 5, 6]; console.log(array1.toString() == array2.toString()); // true console.log(array1.toString() === array3.toString()); // false In the above code, we initialized three arrays and then we applied the toString() method on the arrays and first compared the array1 to array2 and returned the result in the console. In the same manner, we compared array1 to array3 and console log the result: From the above output, we can see that “array1” is equal to “array2” but “array1” is not equal to “array3”.

 Method 2: Using for loop

Let us go through another method in which we will manually check the elements of two arrays and then generate an output. For this purpose, let me show you the code first: function compareArrays() { const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; // First, check the length of both arrays // if length is not equal then arrays are different if(array1.length!=array2.length) return "False"; else { // check every element of the two arrays for(var i=0;i<array1.length;i++) if(array1[i]!=array2[i]) return "False"; return "True"; }} console.log(compareArrays()); // false In the above code, we have defined a function where we initialized two arrays first. Afterwards, we set a condition to check the length of the arrays. If the two arrays’ length is not equal then that means the two arrays are different hence the function will return false. However, if the length is the same then we have set a for loop where we will check every element of both the arrays. If even one element is not equal then False will be returned. If all the elements of both arrays are matched then it will return true. The output of the above code is shown below: If we change the code a little bit by providing two arrays that are equal e.g: function compareArrays() { const array1 = [1, 2, 3]; const array2 = [1, 2, 3]; // Check length of both arrays // if length not equal then arrays are different if(array1.length!=array2.length) return "False"; else { // check every element of the two arrays for(var i=0;i<array1.length;i++) if(array1[i]!=array2[i]) return "False"; return "True"; }} console.log(compareArrays()); // true The following output will be generated:

 Conclusion

We cannot compare two arrays using the equality operator == or === because JavaScript arrays are objects and hence reference is checked and not values. For this purpose, we defined two methods in this post to compare arrays. In the first method, we used the built-in method toString() where we converted the arrays to string first and then checked the two returned strings using the equality operator. In the second method, we first manually checked the length and then compared all the elements of the two arrays one by one using the for loop.

How to calculate the days between two dates?

Have you ever been in a similar scenario in which we are given the joining date of an employee who has resigned from his/her designation on a certain date and we want to figure out how many days he/she has worked with the company to calculate his/her salary. In such a situation JavaScript can help. That was only one out of a gazillion possible scenarios that you can find yourself in, but there are other issues that can take place when dealing with real-life problems. Therefore, we will be discussing how we can easily solve this problem using javascript.

 Calculate days between two dates using javascript

Let’s take a look at how we can calculate the number of days. We’ll start by defining two date objects. let date_1 = new Date('10/25/2021'); let date_2 = new Date(); Then we’ll have to figure out what the difference is between these two dates. let difference = date_1.getTime() - date_2.getTime(); console.log(difference); Now, the result is in milliseconds and we must convert this result to days. The formula for converting milliseconds into the days is: (1000 milliseconds * (60 seconds * 60 minutes) * 24 hours) let TotalDays = Math.ceil(difference / (1000 * 3600 * 24)); console.log(TotalDays + ' days to world Cup'); This will calculate the days between the given two dates.

 Complete code

Following is the complete code for this problem: let date_1 = new Date('10/25/2021'); let date_2 = new Date();const days = (date_1, date_2) =>{ let difference = date_1.getTime() - date_2.getTime(); let TotalDays = Math.ceil(difference / (1000 * 3600 * 24)); return TotalDays;} console.log(days(date_1, date_2) +" days to world cup"); Just run the file and see the output in your terminal, the output will be similar to the following:

 Conclusion

Days can be calculated between two dates by first finding out the difference of time between the two given dates which is resulted in milliseconds and then by converting the milliseconds into the days. In this post, we have learned how we can easily calculate the dates between the two dates using the getDate() property of the Date object.

Apply vs. Call

JavaScript was created by Brendan Eich in 1995 and is a scripting language that is based on the object-oriented programming paradigm making our web pages and web applications more interactive and dynamic. Like any other programming language, JavaScript offers functions that are a collection of instructions in a block to produce a certain result or perform some specific tasks. Functions are objects, and being objects, they have methods. There are a number of useful functions, such as apply, call, and others. The Apply and Call methods are nearly identical, and both are commonly used. In this post, we will cover almost everything related to Apply vs call methods along with examples.

 JavaScript call() Method

The owner object is passed as an argument to the JavaScript call() method, which calls the method. JavaScript uses this keyword which refers to its corresponding object or owner of the function. We can invoke a method that can be applied to a variety of objects.

 JavaScript call() Method Syntax

myObj.myObjMethod.call(myObjInstance, arguments) The myObjInstance keeps track of an object’s instance and at the arguments parameter, we can pass any number of arguments separated by a comma.

 JavaScript call() Method Example

In the below-mentioned example, we created an object having three properties that are first name, last name, and full name. We then create an object myStu and invoke the call method with the owner object. Apart from this, we passed two more arguments (section and grade) with the call method which are separated by a comma. const student = { fullName: function(section, grade) { return this.fName + " " + this.lName + ", section: " + section + ", grade: " + grade; }}const myStu = { fName:"Michael", lName: "Carleone"} alert(student.fullName.call(myStu, "C", "A-"));

 JavaScript apply() Method

The apply() method is used to create generic methods that may be applied to a variety of objects. It differs from the function call() as it accepts an array of parameters.

 JavaScript apply() Method Syntax

myObj.myObjMethod.apply(myObjInstance,[arguments array]) The myObjInstance keeps track of an object’s instance and the second argument is the array that contains all the arguments sent to the method.

 JavaScript apply() Method Example

We will implement the same example that was discussed under call() method example heading. However, it should be noted that apply() method takes an array as an argument rather than multiple arguments separated with a comma. const student = { fullName: function(section, grade) { return this.fName + " " + this.lName + ", section: " + section + ", grade: " + grade; }}const myStu = { fName:"Michael", lName: "Carleone"} alert(student.fullName.apply(myStu, ["C", "A-"]));

 JavaScript call vs apply Methods

So far, we have studied what apply and call methods do. Let us discuss what is the difference between them as we can see from the above discussion that the call method accepts arguments separated by a comma while the apply method accepts arguments in an array. Another difference between apply and call methods is that built-in functions like min and max are used by the apply method, however, the call method cannot use the built-in functions.

 Conclusion

As discussed in this post, call and apply methods are almost similar as both these methods are mostly used for: borrowing and invoking functions in order for the setting of this values. The basic difference between these two is that in apply method arguments are passed in an array however in the call method arguments are passed one after another separated by a comma. Although JavaScript includes a large number of functions, the apply and call functions are the most commonly used. These functions can be employed based on their capability as well as the application or function’s requirements at the time. In this post, we discussed what call and apply methods are along with examples, and at the end, we did a short comparison between the two methods.

Bootstrap vs React.js

If you are a web developer then you must have already heard about Bootstrap and React.js. However, if you are new to this world and want to become a front-end developer whose job is to design the visual features of a web page or web application, then Bootstrap and React.js will be very handy web technologies to learn. Front-end frameworks are very difficult to choose and I myself have been confused about which to choose. So in this post, we will discuss both Bootstrap and ReactJS, their noteworthy features, benefits, and drawbacks.

 What is Bootstrap?

It is a CSS framework that was not even called Bootstrap at the time of its development as it was more commonly known as Twitter Bootstrap because it was built by Twitter. Its latest release came in October 2021 which is 5.1.3. Bootstrap is a framework that is built on the foundation of CSS and CSS3 and it helps developers in making web pages and web applications responsive. Because responsiveness is the key factor for which bootstrap is most known There are various frameworks out there to improve website responsiveness, however, Bootstrap is the most extensively utilized in client-side web development. Popular web applications developed in bootstrap are given below: Paypal Lyft Apple Maps Connect Whatsapp Vogue Magazine

 Bootstrap pros

It allows developers who know HTML and CSS rapid development It provides dozens of components that we can use. One example is the carousel where we don’t need to hard code the functionality of sliding images or videos. JavaScript APIs and Jquery plugins are built-in Bootstrap by default. It offers the reusability of the compatible design components. A wide range of browser compatibility is supported by Bootstrap. It helps in the creation of a cross-platform user interface whose features include responsiveness in style and structure. It is free, open-source, and has gained a vast community.

 Bootstrap cons

Bootstrap has prebuilt styles, so If you don’t spend a lot of time trying to come up with something that would look new, every project would have a similar bland look. It has no compliant-HTML If you are using bootstrap to compile the look of a website then you are basically overwriting a lot of style files, which can sometimes lead to a big mess

 What is React.js?

React.js is not a framework but a user interface library of JavaScript that was developed by Facebook in 2013. React.js was designed mostly for client-side programming and with React.js we can develop interactive fast web applications. It gives us the ability to divide our code into components and hence we can build and create user interface components that are reusable. Components, briefly explained, are the chunks of code that get rendered on the screen. It is fast due to the concept of component, it will only update or refresh the component that we specified and not the whole web page. Popular web applications developed in React.js are: Facebook Twitter BBC Netflix

 React.js pros

Due to the usage of components, it offers us reusability and easy debugging of the code. Dynamic web applications are built using React.js. It improves the efficiency and speed of the web page as components are used and we don’t need the whole page to refresh just the component that we are dealing with. Beginners and professionals both use React, hence contributing to the vast community of React.js.

 Bootstrap vs React (difference)

BootstrapReact.js
To achieve responsiveness, Bootstrap uses CSS grid and flexbox propertiesVanilla JavaScript is used which means simple JavaScript
Used to add responsivenessUsed for improving the user interface
Bootstrap offers classes like col and row size that is dependent on device-widthOffers components and states.
Developers at Twitter that are Mark Otto and Jacob Thornton created BootstrapOriginally created by Facebook
Launched in 2011Launched in 2013
HTML, CSS, JavaScript, SASS were used to develop BootstrapSingle-page applications are created with React.js

 Conclusion

React.js is one of the most commonly known JavaScript libraries. The most prominent use of ReactJs to create single-page applications and improve the user interface. Applications developed in React.js are fast and easily debugged because of the usage of components. On the other side, Bootstrap is a framework used to create mobile-first web applications whose focus is on the responsiveness of the web page or web application. In this post, we discussed what React and Bootstrap are, along with their benefits. In the end, we mentioned the key differences between Bootstrap and React.

What is the difference between JavaScript and Node.js?

JavaScript is a high-level programming language that makes our web pages and web applications dynamic and interactive by giving them the ability to think and act. JavaScript is a lightweight (easy to learn syntax) and object-oriented programming language whereas Node.js is a runtime environment built on google v8 engine and typically used to represent a list of objects and functions that JavaScript programs can access. In this post, we will walk you through what JavaScript and Node.js are, and then we will demonstrate the differences between JavaScript and Node.js.

 What is JavaScript?

JavaScript’s first version was launched in 1995 and it was developed by Brendan Eich of Netscape (then called LiveScript). As discussed earlier, JavaScript is a high-level programming language that has all the functionalities normally a programming language has. JavaScript is an Object-oriented programming language that can be used on the client-side as well as on the server-side and developers not only use it for creating web pages but also it is used for game development and mobile app development.

 What is Node.js?

Node.js was first introduced in 2009 developed by Ryan Dahl and is a runtime environment for JavaScript built on Google’s v8 engine whose main purpose is to run JavaScript on the server and hence JavaScript can be executed outside of the browser. The nicest part about Node.js is that it never blocks I/O, is event-driven, and can be used to create highly scalable apps. In Node.js everything is a module and using these modules developers make use of Node.js in creating web APIs, Rest API servers, command-line applications, and real-time chat applications.

 Difference between JavaScript and Node.js

JavaScript is a proper high-level programming language used to create web scripts whereas Node.js is a run time environment built on google’s v8 engine. JavaScript is executed in the browser whereas using Node.js gives us the ability to execute JavaScript outside the browser. JavaScript can manipulate DOM or add HTML within whereas Node.js doesn’t have the capability to add HTML. JavaScript is mainly used to create front end web applications or develop client-side whereas Node.js is used on the back end development that is server-side development JavaScript follows the standard of JavaScript when writing programs whereas Node.js is written in C++ while using the v8 engine, it runs JavaScript outside the browser. JavaScript requires any running environment as it can execute on any engine such as Firefox’s spider monkey, v8 engine of google chrome, JavaScript core of Safari whereas Node.js runs only on the v8 engine of google chrome.

 Conclusion

JavaScript is a high-level, lightweight (easy syntax) and object-oriented programming language that is used by almost every web developer to create web pages, web applications, mobile applications and is also used in game development. Node.js is a JavaScript runtime environment built on google’s v8 engine which is used to run JavaScript outside the browser and to put it simply it is just an extension of a JavaScript library with many modules hence making JavaScript even more powerful. In this post, we saw what JavaScript and Node.js are and then we described the differences between them. It should be noted that for any web developer the first step is to learn JavaScript and then go for Node.js.

How to setup Visual Studio Code for JavaScript

JavaScript is a web object-oriented programming language that is used in web browsers to produce interactive effects by making our web page act and think. An IDE full form is an integrated development environment and it allows programmers to combine the various parts of building a computer program into one convenient location. It provides local build automation, a source code editor, and a debugger. One of the best IDEs used by almost every developer of JavaScript is Visual Studio Code. Visual Studio Code supports over 40 programming languages and is a free cross-platform text editor mainly used for front-end development. It is a product of Microsoft and can be used in almost all the major operating systems like Linux, Windows, and macOS. Visual Studio Code is widely used for JavaScript development as it is lightweight yet has powerful inbuilt features like IntelliSense (code quicker as it shows intelligent code completion), formatting, refactorings, code navigation, debugging, and much more. We’ll look at how to set up Visual Studio Code for JavaScript in this post. Let’s take the first step, which is to install Visual Studio Code in our Windows.

 Visual Studio Code Installation

To install Visual Studio Code, first, we have to download it from the below-mentioned link: https://code.visualstudio.com/ When you visit the above URL, you’ll see a blue button that will say Download for Windows. Click on this button. When you click the blue button, downloading will start: Once your download is finished, click on the downloaded file shown in the above screenshot. Once done, you will see a window pop up which is a License agreement for Visual Studio Code. Select the “I accept the agreement” option and then click on the Next button: The next window that will pop up will be for selecting additional tasks. Select all the options you need and then click on Next button: Once you click the Next button, the Ready to Install window will show up where you have to click on the Install button: The installation will now start: Once the installation is complete click on the finish button and your Visual Studio Code will launch.

 Setup Visual Studio Code

Now that we are done with downloading and installing Visual Studio Code, let us set up our editor for JavaScript. The first step in setting up our Visual Studio Code is to install the required extensions, which will help us code efficiently and quickly. The extension icon is present at the left shown in the below screenshot: Once you click the extension’s icon, search for the desired extension you want to install. Let’s install the LiveServer extension which is very useful as it has the automatic live reload feature. We don’t need to save our file, it will automatically save and show the output on our browser whenever we make changes to our code. Search the Live Server in the extension tab and click on the below-mentioned icon: Once you click on the Live Server, you will see the install option on the right-hand side. Click on the install button to install Live Server: Once you click on the install button, your Live Server will install: Another extension we can install in our Visual Studio Code is the JavaScript (ES6) code snippet which is very useful as this extension comes in numerous built-in code snippets. The procedure for installing ES6 code snippets is the same as installing the Live Server extension.

 Conclusion

JavaScript is a web programming language that makes our web applications and web pages dynamic and interactive by giving them the ability to think and act. To code efficiently and quicker, a developer needs an IDE. IDE is software where common developer tools are combined and are available in a single GUI interface. One of the best IDE used for JavaScript is Visual Studio Code that offers powerful developing tools and features such as code completion, IntelliSense, debugger, and much more. In this post, we set up Visual Studio Code for JavaScript by first downloading and installing it and then installing extensions in the Visual Studio Code IDE.

How to send an email using JavaScript?

JavaScript is a web programming language that makes our web pages and web applications interactive by giving them the ability to think and act. SMTP.JS (Simple Mail Transfer Protocol) is a JavaScript library that helps us send data or in our case email to a specific server. However, it should be kept in mind that it will only be used to send emails so it will only work with outgoing emails. In this post, we will see how to send an email using JavaScript and with the help of SMTP we will achieve our goal.

 Prequiresites

There are two things you need before we start coding. First, you have to change the Gmail account settings that you will use to send an email such as if 2 step authentication is set up on your Gmail account then revoke it and then allow less secure apps to access Gmail which we can achieve by visiting the Gmail Settings page. Turn on less secure apps:

 Sending Email using JavaScript

HTML: We will first design the structure of our web application. For that copy or type the HTML code in your favorite editor. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Send Email</title></head><body> <form method="post" name="Form"> <input type="Email" name="sender" placeholder="sender123@gmail.com"><br> <input type="Password" name="password" placeholder="type password here"><br> <input type="Email" name="reciever" placeholder="Reciever321@gmail.com"><br> <input type="text" name="Message" placeholder="Enter Email Content" id="Message"><br> <input type="button" value="Send Email" onclick="sendMail()"> </form> <script src="https://smtpjs.com/v3/smtp.js"></script></body></html> In the above code, we used the input tags of HTML to define input boxes for sender email and password and receiver email. Apart from that we also defined a button that says Send Email and initiated an event listener that will continuously listen for the click event which means every time a user clicks on the Send Email button the sendMail() function will start executing. All of the input fields are then placed in a form tag which has a method of post and the name of Form. We will use this name to get the values of input fields of this Form. In the end, we used the script tag to include SMTP protocol and then another script tag to reference the JavaScript file(code.js) that has the function sendMail(). JavaScript:, we initiated the sendMail() function and then stored all the values of the input fields defined in HTML. We achieve this task by referencing the input fields with the name they were given earlier in HTML. After getting all the values, we will send the email using these values. If the process of sending an email is successful we will see an alert of Email Sent Successfully. function sendMail() { //getting values from input fields var sender=Form.sender.value; var password=Form.password.value; var receiver=Form.reciever.value; var content=Form.content.value; //Sending email Email.send({ Host: "smtp.gmail.com", Username: sender, Password:password, To: receiver, From: sender, Subject: "Check Email Sending", Body: content, }).then(function (message) { alert("Email sent successfully") });} Fill all the required credentials and then click on the Send Email button: Now go to your Gmail account and you will see that you have received an Email:

 Conclusion

JavaScript is a programming language in which we can develop and design web pages. The SMTP library is a simple mail transfer mechanism that is used to send emails. In this post, we answered the question of how to send email using JavaScript by first defining our web application structure using HTML, and then we went on to JavaScript to implement the proper functionality.

How to search a string using the match() method?

JavaScript is becoming one of the widely used programming languages in the entire field of AAA quality web applications, and this is because of its availability on almost every modern-day browser. And the fact that there are thousands of frameworks written that allow developers from all around the globe to develop top-tier web, android, and even iOS supported applications. String operations are the basis of many major and famous applications and web frameworks. From comparing passwords to checking the correct username, from accepting a captcha code to confirming a correct email address. Everything is done using string operations., there are many string comparison operations available, but out of all of them, the most intriguing one is the .match() method. What we are going to do is cover all about the .match() method and look at a new method similar to this one as well.

 Definition and Usage

The .match() method is a function to all JS versions. This .match() compares strings with a regular expression (regex). Or in other words, we can say that it is used to search string objects with any regex. If the match is found against the regex, then this method returns an array of all matches else it returns NULL. Syntax string.match(regExp) Parameters: The parameter of this method is a “regExp”, which means a regular expression to compare against the given string. Return Value: It will compare the string with the regex and return an array of all the matches it can find. Otherwise, It will return NULL. Example: var string = "Hello World!"; console.log(string.match(/ello/g)); Output: It returns an array of all matches of “ello” in the string variable. Also, “g” in the code is a flag that tells the method to search for all possible matches in the string and to not stop at the first match.

 What is a Regular Expression:

If we are to define regular expressions in the official words of MDN, it would be: ” The patterns used to match character combinations in strings”. Patterns can include not only alphanumeric characters but special characters, different ranges of groups, and even special characters. Well, to wrap up defining what a regex is, we can say that on the very basic level, it’s about finding a pattern in a given string. The use of this regex can be found when we want to find a specific character from a string, or even when we want to verify that the format of email entered while filling up a log-in form is an actual email address with “@” and “.com” at its end.

 Different matching modes (flags)

The first is (as shown in the above example) using a global flag “g”, which returns an array of string objects. Code: var string = "Hello World!! hello!"; console.log(string.match(/ello/g)); Output: The next example is without the use of a global flag: Code var string = "Hello World!! hello!"; console.log(string.match(/ello/)); Output Even though there are two matching strings against the regular expression “/ello/”, the .match() method only stops at the first match. The next is using the case-insensitivity flag “i”. This flag ignores the case sensitivity of the string and tries to find the match by considering the whole string and the regex in the lower case. var string = "Hello World!! HELLO! HELLO"; console.log(string.match(/ello/gi)); Output In the array which is returned by the .match() method. We can see that it contains both lowercase and upper case strings that matched the regex.

 The .matchAll() method

We have thoroughly learned about the .match(), and we know that the world is constantly evolving in every field, it’s worth pointing out that the .matchAll() has also been added in the newer version of JavaScript. The .matchAll() utilizes the flag “g”, which by now you are familiar with (the global flag), and returns either an iterator or an empty array: Example let regex = /s(h)(ow(\d?))/g; let String = "show1show2show3"; let array = [...String.matchAll(regex)];for (let i = 0; i <array.length; i++) { console.log(array[i]);} Note: We used a for loop to print all the elements present in the array variable. Output: Well, the main reason for using the .matchAll() method can easily be seen. We can see this from the output that it is to used for the improved access to capture groups

 Conclusion

After this tutorial, you probably now are familiar with the working of the .match() method, along with a basic understanding of regular expression and you have also learned about the newly added method which is the .matchAll() method. This means that you now have a basic understanding of matching strings with regex using in-build JavaScript functions. These sure were pretty basic and simple examples, but still showed the purpose and working of the methods.

How to run JavaScript in PHP?

JavaScript is a client-side web programming language that gives our web applications and web pages the ability to think and act by making them interactive and dynamic hence validating client details. PHP stands for PHP: Hypertext Preprocessor and is an open-source server-side (executed on the server) programming language that handles all the processing and managing of the back end and is embedded within HTML. When we combine both PHP and JavaScript functions, we can develop the most dynamic web page or web application. Suppose PHP is a paintbrush that paints a picture then JavaScript provides the color for the paint. So, in this post, we’ll look at how to run JavaScript in PHP.

 Run JavaScript in PHP

Let us go through an example where we will call a JavaScript function from PHP but first, we have to link JavaScript with HTML using the script tag of HTML. Within the echo command, PHP treats every HTML element as a string. As a result, we’ll call the JavaScript functions from within the echo command as shown below: <!DOCTYPE html> <html lang="en"> <head> <title>JS and PHP</title> <script type="text/javascript"> function jsFunction(){ alert('Execute Javascript Function Through PHP'); } </script> </head> <body> <?php echo '<script type="text/javascript">jsFunction();</script>'; ?> </body> </html> In the output we will see the alert shown below: We can also execute JavaScript code within the PHP tags by making the script tag and whatever is inside the script tag as a string and then we will send it to the client browser which will execute it. The following code demonstrates this: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JS and PHP</title> <?php echo '<script type="text/javascript"> alert("Execute Javascript Code"); </script>'; ?></head><body></body></html>

 Conclusion

JavaScript is a client-side programming language that means it deals with the execution of the scripts whereas PHP is a server-side programming language which means it deals with the backend of our web application or web page and is executed by the server. To develop the most dynamic web application or webpage, PHP and JavaScript functions are combined. In this post, we discussed how to run JavaScript in PHP using two methods.

How to resolve the “node is not recognized as an internal or external command ” error?

Node.js is a powerful run-time environment based on Google’s v8 engine that is responsible for making fast and scalable web applications like streaming, chat apps, browser games, command-line applications, and much more. However, as a programmer, you cannot escape from errors. One such error based on Node.js is shown in the below screenshot: You can see we are encountering node is not recognized as an internal or external command error.

 Error Causes

Two of the main reasons due to which you can encounter the above-mentioned error are: Node.js is not installed on your system Environment variables are incorrectly set

 Install Node.js

To properly install Node.js, open your favorite browser and visit the official Node.js website. Click on the windows installer shown in the below screenshot. Your Node.js installer will start downloading and once the downloading finishes, navigate to your downloads folder and click on the Node.js installer. Keep on clicking the Next button until your Node.js gets successfully installed. To verify installation open cmd on your system and execute the below command: $ node -v

 Set Environment Variables

Sometimes even after successful installation of Node.js, the error keeps on appearing; this is because the environment variable is not set properly. To set the environment variable, simply search for edit the system environment in the search bar at the below-left corner of Windows 10. Click on the edit system environment variables, a window will open where you have to click on Environment Variables. The Environment Variables window will open where you have to select or double click on the variable Path. Now paste the complete path where Node.js was installed. Click on ok and restart your system. You can find the path of Node.js by searching node in the search bar located at the left bottom corner of windows 10. You’ll see the node application, right-click on the node application and then click on an open file location. The file location of Node.js will open and you have to copy the path shown in the below screenshot: Once done, open the command prompt and execute the below-mentioned command again: $ node -v You will see the Node.js version installed on your system and the error has been terminated.

 Conclusion

The server-side platform for generating web applications and web pages is Node.js. Node.js may easily be used as a server-side proxy, allowing it to manage a huge number of simultaneous connections while being non-blocking. It’s very useful for proxying numerous services with different response times or gathering data from various sources. You may encounter the error of node is not recognized as an internal or external command when you run commands in your visual studio code editor or any other editor. In this post, we provided two methods by which you can resolve the “node is not recognized as an internal or external” error that is properly installing Node.js and the second method was to set the environment variable path.

How to remove an event Listener? | Explained with examples

JavaScript is highly used in web page development. Being a dynamic language, it’s easy to change the behaviors of the page on Runtime. It is normally easier to use in the client-side environment as we are able to make changes very quickly. Today we are going to talk about another JavaScript operation which is how we can easily remove the event listener from an event.

 Removing the event listener using JavaScript

Removing the event listener from a specific HTML element can be so important in some cases as you don’t want the event to get triggered multiple times without any reason. JavaScript can be very helpful to achieve this functionality so let’s see how we can easily get this job done.

 RemoveEventListener() method

RemoveEventListener() is a built-in function that can be used to remove event listeners from HTML elements.Assume you have the following event listener attached to a <button> element: <body style = "text-align:center;"> <center> <button id="click">Click me</button> </center> <script> let btn = document.getElementById('click'); const clicked = (e) => { alert('this button was clicked'); } btn.addEventListener('click', clicked) </script> </body Now suppose you want to remove the click event from the button, you’ll need a reference to both the element containing the listener and the callback function reference to remove an event listener effectively. To remove the “click” event, the code will go like this: btn.removeEventListener('click', clicked) However, it’s not a good idea to pass an event listener an unnamed callback function like this: btn.addEventListener('click', (e)=>{ alert('this button was clicked'); }) You won’t be able to remove the event listener without the callback function name, as seen in the example above.

 Removing the event listener after clicking the button

Sometimes you may don’t want the button to be clicked twice as if its going to be clicked, the event will trigger and cause the processing issues under the event. So to handle this issue instantly we need to attach a removeEventListener() inside the addEvenetListener() method. Let’s see how we can achieve this functionality in the code below: <body style = "text-align:center;"> <center> <button id="click">Click me</button> </center> <script> let btn = document.getElementById('click'); const clicked = (e) => { alert('this button was clicked'); btn.disabled=true; // this line is disabling the button btn.removeEventListener('click', clicked) // this line removes the event listener right after clicking the button } btn.addEventListener('click', clicked) </script> </body> Output: So with the above example, once the button was clicked, it’s going to trigger the event attached to it and remove that event after disabling the button to avoid multiple clicks at the same time from the user. That’s how you get rid of JavaScript event listeners from HTML elements. For removing an event listener from an HTML element, you need to take care of the two things, you have to define the type of the event and the second thing is that you need to provide the reference function that is attached to the event listener.

 Conclusion

The removeEventListener() method is used whenever you are required to remove the event from a particular HTML element. This method requires two arguments,the first argument will be the event name while the second argument will be the function that is attached to the event listener. In this article, we have seen the example where we have discussed how we can simply remove an event attached to an HTML element.

How to remove a character from a string using replace() method?

JavaScript is a programming language that is used to build web pages and web applications and make our web pages dynamic and interactive by giving them the ability to think and act. JavaScript offers us primitive data types which are predefined used to store data temporarily. One such datatype is a string that is textual content enclosed in double or single quotation marks. String datatype offers us different properties and inbuilt methods that we use to manipulate and play with the string. One such example is the replace() inbuilt method of the string.

 What is the replace() method?

The replace() is an inbuilt method of JavaScript that replaces a character or string with another character or string in a specified string. First, it searches the character/string and then replaces it with the string/character we set. It should be noted that the replace() method does not change the original string and always returns a new string. The syntax of the replace() method is: myString.replace(valueToBeReplaced, newvalue); The JavaScript replace() method takes two arguments that are valueToBeReplaced and the newValue which is the value you want to replace it with. myString is the specified string where we are searching and replacing a value.

 Removing a character

Now that we know what replace() method of JavaScript is, let us come to the main topic, which is how to remove a character from a string using the replace method. For this, suppose, you were writing a string and you mistakenly added a character in the middle and you want to remove that character, how will you do it? The answer is very simple that is we just have to provide an empty string in place of the second argument of the replace method(newValue): var myStr = 'Hello y Nas'; console.log("original string:",myStr); // Hello y Nasvar newStr = myStr.replace('y', ''); console.log('After character removed: ', newStr); // Hello Nas In this code, first, we initialized a string, and then console logged that string. Then we used the replace() method on the original string and removed the character y from it and the new string that is returned is stored in newStr. After that we console log the new string: Now suppose you have added two-three characters by mistake hence we can also remove a string from a string using the replace method in the same manner: var myStr = 'Hello wy Nas'; console.log("original string:",myStr); // Hello wy Nasvar newStr = myStr.replace('wy', ''); console.log('After string removed: ', newStr); // Hello Nas Now that we know how to remove a character or a string from a specified string, let us use the replace() method with regular expressions. In the previous examples, the drawback of the replace method was that it only removed the first occurrence of the specified string or character in the original string. To overcome this drawback, we use the regular expression from which we can remove every instance of a specified character or string. var myStr = 'I have two blue shirts and two blue caps'; console.log("original string:",myStr);var newStr = myStr.replace(/blue/g, ''); console.log('After character removed: ', newStr); We used the /blue/g which means it will remove every instance of blue in the myStr string:

 Conclusion

The JavaScript replace() method is an inbuilt method that replaces a character or string in a specified string and returns the new string. The replace() method gives us the advantage of manipulating and playing with strings. One such advantage is that using the replace() method we can remove a character or string from an original string. We can also remove all the instances of a character or string in a specified string. In this post, we first defined what replace() method is and then we went on to see how to remove a character from a string using the replace() method of JavaScript.

How to practice JavaScript

Javascript is the most commonly known programming language that has been in the market of technology for almost two decades now. Sometimes, it is better to know when something was created to know the dominance it holds over the current day IT market. Well, Javascript was created in 1995, but it wasn’t released in 1995. In early 1996, JavaScript was released to the market. At that time, in 1996, Javascript wasn’t called “JavaScript”, it was called “LiveScript”, and by the end of 1999, it reached some popularity. But, two decades later, it is the most searched programming language at the end of the year 2020 according to google. You can visit their official website here. JavaScript had no concept of input\output, as it was not a normal programming language, it was created to be a “Scripting Language”, a language only capable of running various scripts. Despite how it started, JavaScript is now a globally used language that has almost everything in it. If there is something that JavaScript is lacking, there is either a package of JS that is completing that void or the package is under development. According to wiki: around 97% of the websites available on the internet use Javascript in some form. You can read more about JS on the wiki by clicking here.

 Why do you need to practice JavaScript?

If you are starting to learn how to become a programmer or if you are already familiar with what programming is, you would know JavaScript, as again, it is the most commonly used and the most popular programming language of the current day market. And if your dream is to have a source of income from being a programmer, then learning JavaScript can be called a “crucial” step. To answer the question – “Why do you need to practice JavaScript?” – To put it simply, even if you are starting your programming journey with JavaScript or even if you are already a JavaScript pro, you have to keep practicing or else you will lose the touch.

 New to JavaScript?

Now, if you are new to JavaScript, or even new to programming, then you might be wondering how to get started with JavaScript because if you google javascript it will show you a million search results, and that is overwhelming. You can get started with JavaScript, by going to linuxhint’s extensive library of articles on javascript, by clicking here, and if there is anything that you want to know about, which belongs to JavaScript in general you can always check out the official docs at the Mozilla developer network web docs (or MDN Web Docs) MDN Web Docs Also, you might want to get these things set up.: Online Editor \ Browser’s console: If you are just starting out then use online code editors Set up a code editor: You need to set a code editor, the most commonly used is Visual Studio Code Choosing a browser (compatible with latest JS)

 Already familiar with JavaScript?

Do you already have a keen understanding of JavaScript?, and you are wondering how to stay in touch with JavaScript or to become a better programmer in general. If that is your case, then you should focus on certain programming concepts and practices, which will help you grow as a programmer when working as a full-time developer at a professional firm. These concepts and practices include the following: OOP: By far the most widely used programming concept is Object-Oriented Programming, read more information about JavaScript and OOP. The concepts of classes, objects, objects accessors are really important to grow as a programmer. Following a Convention: Convention is not a hard and fast rule, but, they are more like programming guidelines to write a similar style of code. Single Responsibility Classes: “A single class should have one and only one reason to change”, what this means is that a class should perform only one responsibility at max. Start Documenting Your Code: Documenting your code is considered to be the most crucial step while working in an international-level software firm. So, start putting up documentation with almost every important block of code.

 How to become a pro

Well, the only real way to become a pro in JS is to build projects. Building projects may seem daunting at first, but think about it this way, if you are facing any issue, then why don’t you come up with a solution with the software of your own rather than downloading software from the internet. This type of approach will also fill up your head with a lot of ideas to implement – because the hardest thing to do for a programmer is to think of ideas to implement. Keep in mind, when developing newer projects, you need to utilize more and more packages and functions to get a good grasp on them. You can learn something new about JavaScript from here. Also, there is also one fact that you can never argue with, and that fact is “No one is perfect”, and if no one is perfect then how can their code be perfect as well. So, one really good practice to become a pro at JavaScript is to revisit your old code and be very critical of it. And, once you notice your silly mistakes, then improve that code. One major step, for being up-to-date with new packages for JavaScript or even new features of JavaScript itself, is to join JavaScript communities, Join discord servers, and by taking part forums.

 Explore Frameworks

JavaScript is famous for one thing and that is Frameworks, they are available for almost every problem. You want to develop a mobile app – well, good news for you, there is a JS framework for mobile development too. Or maybe, you want to develop a server-side application for some web-app for mobile, well… what do you think? , there is a framework available for that. So, explore more and more frameworks, and choose the field that you want to jump into. It can be web-app development, perhaps only iOS development, or even server-side development. Once you know, which field do you want to conquer, then you can bee-line your focus on only those frameworks that help you become a pro in that specific field.

 Conclusion

Everyone interested in learning programming, or even expert programmers, want to stay up-to-date with modern-day technologies, which would be JavaScript at the time of writing. Well, you should always practice something to either develop an understanding about it or to become a pro in it. And, that is exactly, what we went through with – how to practice JavaScript, regardless of your skill level. We covered things like what to do if you are new to JS. Or, how to keep improving as a programmer, and how to adopt practices that are used in major programming firms.

How to map an array array map method | Explained with examples

Like any other programming language, JavaScript provides us with various data types to store data. One such data type is an array. An array is a group of elements that can be used to store several values in a single variable. JavaScript offers us Array object methods that we can use to manage, organize or access data stored in arrays. One such in-built method of the array object is the map() method.

 What is the map() method?

The JavaScript array’s map method creates a new array by calling a call-back function(passing a function to another function as an argument) on each and every element without changing the original array. The Syntax of the array map method is shown below: myArr.map(function(currentValue, index, arr), thisValue); As we can see from the above syntax, the map() method takes two parameters. The first is function(currentValue,index,arr) which is a callback function and is a compulsory parameter. This call-back function takes three arguments. The first is the currentValue referring to the current value of the element and it is a compulsory parameter. The second parameter is the index which has the index of the current element and the third is the arr which refers to the array. The index and arr parameters are optional. The next parameter in the map() method is thisValue which refers to the value that is passed to the function and thisValue parameter is optional.

 Iterating over an array using the map method

Now that we know what an array map method is, let us see how to iterate over an array using the map method. var myArr = [1,2,3,4];var newArr = myArr.map(function(element){ // multiply myArr with 2 //returns a new array return element *2;}); console.log(newArr); // [2,4,6,8] In the above code, first, we initiated an array with the name of myArr and then called map() method on this array initiating a call back function. In the call back function, we multiplied each and every element of the myArr to 2. We then saved the new array to the newArr variable and then console log the new array whose output is shown below: Let us see some other examples of the map() method.

 Rounding array elements

In this example, we will see how we can round array elements to the nearest integer. var myArr=[2.3,3.7,4.4]; var output=myArr.map(e=>Math.round(e)); console.log(output); // 2,4,4 We first initiated an array with the name of myArr and then initiated the map method on this array by rounding off every element of the myArr and then the output of this operation is saved in the variable output.

 Finding Square root

Let’s find the square root of all the elements of an array for which it is mostly the same as the above example. First, we will initiate an array and then run the map method on it, storing the result in the output. var myArr=[4,9,16]; var output=myArr.map(e=>Math.sqrt(e)); console.log(output); // 2,3,4

 Adding String to the array elements

In this example, we will add the string 1 dozen with every element of the array. For example: var myArr= ["banana", "apple", "orange"];var output= myArr.map(e=>"1 dozen "+e); console.log(output); We can see in the output that every element of the array now has 1 dozen in the new array that is console logged.

 Getting Full name from an array of objects

Let us see a little complex example where we will initiate an array of objects that will contain the first name and last name of a person. We will then execute the map() method on this array and then in the call back function we will concatenate the firstName and lastName to get a fullName of the person. const persons = [ {firstname : "John", lastname: "Reynolds"}, {firstname : "Smith", lastname: "Jhonson"}, {firstname : "Sarah", lastname: "Frye"}];function getFullName(item) { return [item.firstname,item.lastname].join(" ");} const output= persons.map(getFullName); console.log(output);

 Conclusion

To store data JavaScript gives us various data types such as an array. An array has inbuilt methods that make us easily manage our code and write less code. One such method of the array is the map() method. The array map() method executes a call-back function on each and every element of the array and returns a new array. In this post, we saw how to map an array and what a map method is. Apart from that, we iterated over an array using the map() method and then provided a few examples using the map() method of the array to transform elements of the initiated array according to the provided call-back function.

How to handle time zones code

JavaScript has become the most popular and massively used scripting language. In this modern era, almost every website uses JavaScript. In our daily life, time plays a vital role because if we want to add an update to the application it stamps the backup with the current date and time. Take an example of a blog website. Blogs can use timestamps which help to indicate the date of the comment, publish date, last modified date, and many more. A time zone represents uniform standard time for different purposes in a country. It is quite common for different countries to have a unique time zone, with some large countries like the USA and Canada having multiple time zones.

 GMT

The abbreviation of GMT is “Greenwich Mean Time”.GMT is a local time and became popular in January 1972.

 UTC

UTC is generally a time system that uses the frequency of cesium atomic to synchronize the standard time. UTC and GMT are more or less the same in many cases but in a few cases, UTC gives a more accurate time as compared to GMT.

 Offset

Offset is known as the comparative time between local time and standard time of UTC. Now we are demonstrating how to handle time zones and what are the different ways to include dates in your website. First, we have to create an instance of Date() and assign the object of Date() to a “current_date_obj” variable. Run the below-mentioned lines of code to get the current date. This piece of code will return you today’s time and date of your particular time zone in an object. const current_date_obj = new Date(); console.log(current_date_obj); Output If you want to use an object containing the current date and time then you have to format it accordingly through several Date methods of JavaScript. Run the below-mentioned code if you want to get the current date with a specific format. const date_obj = new Date();const current_date = date_obj.getDate(); console.log("Current Date" + ":" + current_date);const current_month = date_obj.getMonth(); console.log("Current Month" + ":" + current_month);const current_year = date_obj.getFullYear(); console.log("Current Year" + ":" + current_year);return console.log(current_date + '/' + (current_month + 1) + '/' + current_year); Output Formatting a date according to your time zone is a way much easier task. Moreover, if you want to display distinct time zones for several countries on a web application then you need to do some calculations and convert local time accordingly. For instance, we have to implement functionality that gives an alert after every 16 hours according to a particular time zone. For this, below mentioned steps should be followed.
    First of all, you need to convert the date in milliseconds since 1st January 1970. Then you have to get the offset of UTC and convert it into milliseconds. If you add the offset of the local time zone into local time then you get the current UTC time. After acquiring the current UTC time then you need to obtain the UTC offset of the destination city into hours. Convert a value of UTC offset into milliseconds and add into UTC time accordingly. At last, you have to format a date-time string into the readable standard format of Date. For this, you have to convert the value of milliseconds into a new string of Date.
Run the following code to get a different time zone after converting the date. <html><head><script language="JavaScript"> // this is the function in order to compute local time of several cities by passing UTC offsetfunction computeTime(city_name, offsetUTC) { // create new instance of Date current_date = new Date(); // now you need to get UTC time in msec utc_time = current_date.getTime() + (current_date.getTimezoneOffset() * 60000); // create instance of several cities new_date_instance = new Date(utc_time + (3600000*offset)); // in this step you have to return time as a string return "Local time of " + city_name + " is " + new_date_instance.toLocaleString(); }// Pakistantime alert(computeTime('Pakistan', '+5')); // get Singapore time alert(computeTime('Singapore', '+8')); // get London time alert(computeTime('London', '+1')); </script></head><body> </body></html> Output Here is the output of Pakistan’s local time. Here is the output of Singapore’s local time. Here is the output of London’s local time.

 Conclusion

In this article, we explained how to get a date and time and then use it according to our desire in effective and efficient ways which are easy to learn for beginners. We have also elaborated on how we can handle time zones and related to that we have also provided an example that shows different time zones of different countries through Javascript.

How to get the URL of the webpage using JavaScript

When we are developing a web application, URLs are the ones that we commonly have to deal with. URLs are the paths that are needed to redirect the user to a specific page and hence it is necessary to handle the URLs by some specific methods. JavaScript has its own methods to get the URL of the page which returns a lot of useful information like the hostname, pathname, and the query inside the URL. Let’s take a look at this in this article.

 What is a URL?

URL (Uniform Resources Locator) is a path that allows you to access a particular web page instance. The browser recognizes the path and displays the required webpage against that URL. Before jumping into getting the URL of a webpage we need to have a basic knowledge of a couple of objects like: window object location object href object Let’s have a basic understanding of each of these objects.

 JavaScript Window Object

JavaScript uses the window.location.href to get the URL of the page. here the window object is a universal or a global object which is basically a browser’s window and this window object holds all the JavaScript objects, functions, and variables as well.

 JavaScript Location Object

Location object holds all the information of the current URL of the webpage, this Object can be accessed easily by using the window. location.

 JavaScript href Object

The href is a property that can be used to set or return the entire URL of the current webpage we are working on. this property is accessible under the window.location.href Let’s have a look at the entire object and its applications.

 window.location.href explained

In JavaScript, the Location object holds information about the document’s current URL, while the Window interface is used to access it. As a result, you can retrieve the Location object for the current document with Window.location. then utilize the property location.href to retrieve a string containing the whole URL. The current URL shown in the web browser address bar may be retrieved using a variety of JavaScript techniques. You may retrieve this data by using the Window object’s Location object attribute. The following is a list of some of the characteristics of the location object. The operations that you can do using JavaScript are listed below.

 Examples of URL data retrieved using window.location

Let’s take an example URL ‘ https://exp.com:3737/get?post=exp#query’ and perform some operations on it.
Operation Results
window.location.hrefhttps://exp.com:3737/get?post=exp#query
window.location.protocol; https:
window.location.host example.com:3737
window.location.hostname exp.com
window.location.port3737
window.location.pathnameget
window.location.query?post=exp

 Browser Implementation

We have discussed above that how we can easily use some of the built-in JavaScript objects to retrieve the URL and the information lying under the URL like the hostname, pathname, the query, etc. Now, we are going to practically test out how the window.location.href property works and how we can use it to get the URL of the webpage quite easily. JavaScript allows you to get the URL of a webpage using its window.location property. You can simply call the window.location.href property which will return you the complete URL of the webpage including hostname, pathname, and query string. Let’s test the JavaScript property practically. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>URL Tutorial</title></head><body> <input type="submit" value="Click me" id="btn"> <script> var btn = document.getElementById('btn') btn.addEventListener('click', (e)=> alert('The url of this page is: ' + window.location.href)) </script></body></html> Here in the above code, we have created a button, this button has a JavaScript event attached to it which is triggered whenever a button is clicked by the user. In the JavaScript event, we are displaying the URL of the current webpage in an alert by using the window.location.href, this alert contains the message and the current URL of the webpage. Browser output: When we click on the button, an alert pops up which displays the URL of the current webpage: Here you can see that we have used window.location.href inside the code to get the URL of the webpage and return it into the browser as an alert. So whenever you click on the ‘’Click me’’ button you will see an alert on the screen with the message containing the URL of the current webpage.

 Retrieving URL data using JQuery

Until now we have discussed how we can easily get the URL of the webpage by using the JavaScript’s window.location.href property, we can achieve the same functionality with the JQuery as well which is easy to implement and quite reliable as well. The operations that you can do using JQuery are listed below. Let’s take an example URL ‘ https://exp.com:3737/get?post=exp#query’ and perform some JQuery operations on it.
Operation Results
$(location).attr(‘href’); https://exp.com:3737/get?post=exp#query
$(location).attr(‘protocol’); https:
$(location).attr(‘host’); example.com:3737
$(location).attr(‘hostname’); exp.com
$(location).attr(‘port’);3737
$(location).attr(‘pathname’);get
$(location).attr(‘search’);?post=exp
$(location).attr(‘hash’); #query
$(location).attr(‘origin’);

 Conclusion:

In JavaScript, window.location.href is the property that you can use to retrieve the URL of the current webpage. You can easily fetch the current page URL and perform whatever operation you want after grabbing the URL. In this article, we have seen a few operations that we can perform on the URL after grabbing it and we also took a look at how we can implement the method inside our JavaScript code to achieve the functionality.

How to create the “Scroll Back to Top” button

Nowadays, it is an obvious fact that long-structure content is expanding deliberately on the web. As it helps to convey detailed content, exhibit more pictures, and expand SEO. Nonetheless, creating detailed content and neglecting UX will probably put readers away. In order to avoid this problem, you have to insert a back-to-top button which assists you to shift efficiently to the start of the page in seconds. As the name of the button implies, whenever clicked then takes your end users back to the start of the page immediately. Back to top button is appropriate for all gadgets and screens. If the web page contains detailed content then including a back-to-top scroll button is strongly suggested.

 Scroll back button

A button to get back to the topmost of the web page permits the end users to rapidly get back to the start of the web page without putting forth a lot of attempts. This can be exceptionally helpful when the web page has a ton of content, for instance, when the scroll is used to view content on a one-page site. Scroll back buttons are mostly placed in the base corner of websites and afterward return you to the start of the page whenever the user clicked on that button. You make this button easily by using JavaScript. We should check out a couple of ways we can create a scroll back button, start with simple implementation, then, at that point, and further develop things as we go. Now we are going to demonstrate to you a simpler example of how to create a scroll back to the top by using JavaScript. Example In this example, we create a button that scrolls back to the beginning of the page. First of all, you need to click on the arrow button then document.documentElement assists you to return to the start of the page. Furthermore, we also add a little bit of styling of the button and insert a click event with the button which helps to scroll to the start of the web page. The code is illustrated below: <html><head><style> body { font-family: Arial, Helvetica, sans-serif; font-size: 15px;} p{ text-align:justify; padding-left:10px;} #backbtn { background-color: #2596be; color: white; text-align: center; font-size: 30px; text-decoration: none; overflow: hidden; display: none; cursor: pointer; position: fixed; width: 40px; line-height: 40px; bottom: 50px; right: 0;} #backbtn:hover { background-color: #DDF; color: #000;}</style></head><body><button onclick="Scrollback_topfunc()" id="backbtn" title="Scroll back to top"></button><div style="background-color:#2596be;color:white;padding:30px">You are learning scroll back to top button</div><div style="padding:30px 30px 50px"><p> <img src="desert.jpg" style="width:40%; height: 40%; float:right; margin: 0 0 0 15px;">Scroll back button A button to get back to the topmost of the web page permits the end users to rapidly get back to the start of the web page without putting forth a lot of attempts. This can be exceptionally helpful when the web page has a ton of content, for instance, when the scroll is used to view content on a one-page site.Scroll back buttons are mostly placed in the base corner of websites and afterward return you to the start of the page whenever the user clicked on that button. You can easily make this button by using JavaScript. We should check out a couple of ways we can create a scroll back button, start with simple implementation, then, at that point, and further develop things as we go. </p><br></div><div style="padding:30px 30px 50px"><p> <img src="penguins.jpg" style="width:40%; height: 40%; float:left; margin: 0 15px 0 15px;"> Scroll back button A button to get back to the topmost of the web page permits the end users to rapidly get back to the start of the web page without putting forth a lot of attempts. This can be exceptionally helpful when the web page has a ton of content, for instance, when the scroll is used to view content on a one-page site.Scroll back buttons are mostly placed in the base corner of websites and afterward return you to the start of the page whenever the user clicked on that button. You can easily make this button by using JavaScript. We should check out a couple of ways we can create a scroll back button, start with simple implementation, then, at that point, and further develop things as we go.</p></div> <script>var back_top_button = document.getElementById("backbtn");// Whenever end users scroll down 10px from the beginning of the web page, then back to top button visible window.onscroll = function() {scrollfunc()};function scrollfunc() { if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) { back_top_button.style.display = "block"; } else { back_top_button.style.display = "none"; }}function Scrollback_topfunc() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0;}</script></body></html> Output

 Conclusion

JavaScript is the evolving programming language and is used widely by software developers to build intuitive websites. Through this article, you easily learned how to create a scroll back to the top button. We also enlisted a detailed example that assists you to understand the functionality of the scroll back button and how you can use it on your websites.

How to create the “Copy to Clipboard” button

JavaScript is a web programming language that makes our website interactive by giving it the ability to think and act. Copy to Clipboard button is a necessity in many websites for example if you have developed a website that paraphrases your sentences, or your website is a plagiarism remover, or it is a simple text field that lets the user write data online. To improve user experience, websites that provide some information and that information is required in other sections of the website, the website requires the copy to clipboard button. So, looking at all these uses, let us implement a JavaScript program that will answer the question of how to create the copy to clipboard button.

 HTML

HTML is a markup hypertext language that gives structure to our website. We will use HTML to create an input field that will be used by the user to enter some text. Then a button will be created, which when clicked will copy anything that is in the input field. In the end, we will use a script tag to reference the JavaScript file which has JavaScript code: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Comment Box</title></head><body> <input type="text" id="mytext"> <button onclick="handleClick()">Copy</button> <script src="code.js"></script></body></html> We used the id attribute in the input tag so we can reference it later from the JavaScript File. We also initialized the onclick event which means whenever the user clicks on the copy button, the handleClick() function will run.

 JavaScript

We initialized a function with the name of handleClick() so that whenever the user clicks on the copy button the code in this function will start executing. Inside the function, using the id attribute of the input field, we referenced the input field and attached .value in the end so that the input field value is stored in the variable input. Now that we have the value of the input field, let us copy the value to the clipboard using the navigator.clipboard.write() function where we pass the input variable as a parameter. The input variable text is now copied to the clipboard. In the end, we alert the input variable. function handleClick() { /* Save value of myText to input variable */ var input = document.getElementById("myText").value; /* Copy the text inside the text field */ navigator.clipboard.writeText(input); alert("Copied Text: " + input);} We entered the text copy to clipboard article in the input field and now we will click on the copy button. We will see an alert showing the copied text: Go to a new window or a word file and press CTRL+V which will paste the copy to the clipboard article in that window.

 Conclusion

Copy to clipboard button comes in very handy when you are making a website that uses information from one section to another hence improving user experience. Copy to clipboard button is also a project for a beginner who wants to practice his JavaScript skills. In this post, we implemented the copy to the clipboard button along with screenshots and a GIF.

How to create a simple comment box on a web page using HTML, CSS, and JavaScript

To get feedback or any message from a website visitor you need a comment box on your web page. A comment box can be created using any web technology whether it is simple HTML, CSS or even JavaScript. The three tools HTML, CSS, and JavaScript are enough to make fully functional websites. We’ll explore how to make a simple comment box with HTML, CSS, and JavaScript in this post.

 HTML

Open your favorite editor and type or copy-paste the below-given code. Save the file with HTML extension. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Comment Box</title> <link rel="stylesheet" href="style.css"></head><body> <input type="text" id="comment-box" placeholder="Enter comment"> <button id="post">Post</button> <ul id="unordered"> </ul> <script src="code.js"></script></body></html> In the above HTML code, we used the link tag in the head tag to reference the CSS file that we will use later. After this, in the body tag first, we initiated an input box where a user can type their comment. Then a button with the name of the post is initiated which will be clicked to enter a comment. After this, we initiated an unordered list (ul) and left it blank because we will add a li element from JavaScript in this tag. You can also see that we use the id attribute in the above code which will be used to reference the corresponding elements code. The last tag is the script tag where we passed the reference of the JavaScript file which will be attached to the current HTML file. The JavaScript file name is code.js.

 CSS

Create a file with the name of style.css. It should be noted that you can name your file anything but remember to reference that name in the HTML file link tag. Copy and paste the below code in your CSS file: body { background: dodgerblue linear-gradient(45deg, aqua, dodgerblue, deeppink) fixed;} #comment-box, #post { border: none; border-radius: 5px;} #post:hover{ background-color: deeppink;} In the above CSS code, first, we referenced the body tag of HTML and decorated the body background with different colors. Then using the id attribute of the input box, we vanished the border of the input box and gave it a radius of 5px. The same styling was applied to the post button. After this, using the hover property we set a background color of deep-pink for the post button which means whenever a user will hover over the post button its color will change to deep pink.

 JavaScript

Create a JavaScript file with js extension for example code.js. It should be noted that the name of the file should be similar to the one that was referenced in the script tag of the HTML file. In the code.js file, first, we get the HTML button element using getElementById() method and pass the name of the id given to the button in HTML. You can also see an event listener attached to the post which is basically the button element. This event listener will continuously listen and whenever a user clicks on the post button the function within the Event Listener will be executed. var post= document.getElementById("post"); post.addEventListener("click", function(){ var commentBoxValue= document.getElementById("comment-box").value; var li = document.createElement("li"); var text = document.createTextNode(commentBoxValue); li.appendChild(text); document.getElementById("unordered").appendChild(li); }); In the Event Listener function, first, we are getting the value of the input box and after that, we created a li element. To set the text of the li element we used createTextNode and after that using the appendChild method we provided the text to the li element. At last, using the appendChild method we are providing the unordered list of the li element we just created.

 Conclusion

HTML, CSS, and JavaScript are the building blocks for a web developer and many websites are developed using these three technologies. In this post, we provided you with the code and explanation of the code on how to create a comment box using HTML, CSS, and JavaScript. This project will come in handy when you are making to-do lists, comments on a web page or feedback forms as well as attach text to a page in any web project.

How to create a dictionary with key-value pairs?

Most of the time, the databases are used for storing a large amount of data for using it later on or for saving the state of the application but there comes a need to store the data locally inside the code to use it later. Therefore, programming languages have some standard data types which are really helpful in achieving such functionality without using the database.

 Need of key-value pairs

So for this purpose, JavaScript uses arrays and Objects to store some records inside the code. Unlike other programming languages, JavaScript has no exact type to be called a Dictionary, but it does have a diverse type which is called Object. JavaScript’s Object is quite flexible as you can use it dynamically wherever you want. Most of the time objects are widely used for the data as they can be easily utilized later in the code.

 Object

Objects are also the same as Dictionaries in other programming languages as the Objects also consist of the key Value pairs and the dictionaries are also based on this key-value pair formation structure. You can assign a key against a specific value to access it later on. In this article, we are going to see how we can create dictionaries and how we can easily manipulate some data into them with the help of some examples.

 How to create a Dictionary/Object

Because Dictionaries are not the traditional data types of JavaScript hence we use them the same way to create the dictionaries as we declare the objects and initialize some values to them. Let’s take an example for creating the object. Example let myFirstObject = new Object();// or the shorthand way let myFirstObject = { firstName: 'Mark', lastName: 'Fonso', age: 20} console.log('the type of the variable is :',typeof(myFirstObject), 'and its values are :', myFirstObject) There are two basic ways through which you can create an object, the first one is by declaring the name of the object which in our case is “myFirstObject” and then creating its instance by initializing a new Object(). The second way is considered as a shorthand method which is to simply declare the name of the object and assign it some key-value pairs to make the interpreter understand that yes it is an object. Output: Here you can see that the type of object is Object as I said that there is no traditional data type called object hence JavaScript objects are treated as objects in some cases. Let’s take another example of creating a new Object in below example Example let expObject = { firstName : "John Doe", "Ten": 10, 10: "Any Integer", "experience": 0}; console.log('Type: ',typeof(expObject), '\n','Values: ', expObject) Here in the above example, we have created and initialized a new object with the name expObject and console logged it into the terminal while checking its data type and displaying the values inside it. As you can see in the above output screen that the type is being displayed as an Object while its values are also being displayed in the output terminal as we expected.

 Assigning Values to the object keys

We have successfully created our object, now let’s check out the values by using the key names in the below example; This may be accomplished by utilizing the Object’s Indexer property to set the values, or by using it directly as if it were a normal property on the object. The Key values can be any object, not just strings: let expObject = { firstName : "John Doe", "Ten": 10, 10: "Any Integer", "experience": 0}; expObject["Ten"] = 20; expObject[10] = "Twenty"; expObject["experience"] = 22; console.log('Type: ',typeof(expObject), '\n','Values: ', ExpObject)// Assigning property directly dict.firstName = "John Doe"; Here in the above example, we have created an object and later on, we have assigned the values exclusively to the specific properties or keys of the object by using the indexer method. Output You can now clearly see in the above provided output screen that the values have been updated in the object.

 Assigning values to the object using the dot operator (Direct Assignment)

Till now we have discussed how we can create objects and how we can assign some values to the properties of the object using the indexer method, here in the below example we will see how we can use a dot operator to assign some values to the properties of the object. Example let expObject = { firstName : "John Doe", "Ten": 10, 10: "Any Integer", "experience": 0}; expObject.Ten = 20; expObject.experience = 10; expObject.firstName = 'Mark Huggy'; console.log('Type: ',typeof(expObject ), '\n','Values: ', expObject ) Here in the above example we are creating a object and later on we are assigning some values to its properties using dot operator or you can say a direct assignment in other words. You can see that the above-highlighted values are updated in the object.

 Iterating key-value pairs of the object

Now we will discuss about iteration of the key-value pairs. Example Here in the following example, we will create an object and then we will loop through each key of the object and display the value against each key of the object: let expObject = { firstName : "John Doe", "Ten": 10, 10: "Any Integer", "experience": 0};for(let key in expObject ) { let value = expObject [key]; console.log(value); } Output The values are being displayed against each key with the help of a for loop

 Direct Access to Key/Value Pairs

Same as direct Assignment, We can also directly access the values of the object using a dot operator and assign it to some other variable for later usage. Let’s see in the below example: let expObject = { firstName : "John Doe", "Ten": 10, 10: "Any Integer", "experience": 0}; let first_name = expObject.firstName; expObject.firstName = "Mark Christonson"; console.log('Old name :',first_name, '\nNew Name: ', expObject.firstName ) Here in the above example, we have created an object and later, we have assigned its old firstName value to the first_name variable and updated the value of the firstName by using the direct assignment method. Later on, we have displayed both the old and the new values in the screen Output: You can see both the old and the new name fields in the above output screen.

 Conclusion

Dictionary is not the traditional data type of the JavaScript programming language, but the objects can be treated as dictionaries in some cases. You can create an object through two different ways, one is to declare it and initialize it using the new Object() method and the second one is the shorthand way by simply declaring and assigning some key-value pairs to it. In this article, we went through both methods in detail and we have discussed how we can assign and retrieve values using direct assignment and indexer methods.

How to count the number of days between two dates code?

There are times when you are coding an app, you are required to count the number of days between two specific dates. For example, you are creating an application for a library and in that app, you have to calculate the number of days when someone returns a book or when a member’s subscription is required to be renewed, or when a new event comes up. In JavaScript, to calculate the number of days between two dates we can use the date object hence let us start our article by defining what a date object is.

 What is a Date Object

Date object is a built-in JavaScript method that allows us to work with dates and times and is initialized with the keyword new. An example of initializing a date object is given below: const myDate = new Date(); // declaring date The new Date() will create an object that will have the current date and time: const myDate = new Date(); // declaring date console.log(myDate); It’s also worth noting that the Date object just represents the amount of milliseconds from January 1, 1970.

 Count Number of days between two dates

Now that we know what date the object is, let us go through an example where we will count the number of days between two Dates. For this purpose, we will first define a function with the name of getDays() and pass two arguments to this function i-e a starting date and an ending date as strings. Then in this function, we will perform other operations to calculate the number of days between the starting and ending days: function getDays(start, last) { //initialize dates with Date object const date1 = new Date(start); const date2 = new Date(last); // calculation for converting a day into milliseconds const oneDay = 1000 * 60 * 60 * 24; // calculation for the time difference between start and last const diffTime = date2.getTime() - date1.getTime(); // calculation for the days between start and last const diffDays = Math.round(diffTime / oneDay); // return number of days return diffDays;}const myDate= new Date(); // current time that is 10/26/2021 console.log(getDays("2/1/2021", "3/1/2021")); // 28 console.log(getDays("10/24/2021", myDate)); // 3 In the above code, inside the getDays() function we are first declaring two dates using the arguments passed in the getDays() function. After that, we are calculating milliseconds for one day and then the difference in time between the two days. Finally, we are calculating the number of days between the two dates, storing the value in diffDays, and in the end, we return the diffDays variable. Outside the function, we initialized a Date object which will store the current date and time and then we called the getDays() function inside the console log by giving the getDays() two date arguments as strings. We also call the getDays() function with a random date and myDate arguments. The result is as follow:

 Conclusion

Counting the number of days between two dates is a good practice program for a new JavaScript developer. Creating a program that calculates the number of days between two dates is very helpful in applications where you have to calculate the number of days and also it helps in getting acquainted with the Date object of javascript. In this post, we first taught you what a date object is, and then we went on and told you how to count the number of days between two dates using the Date object.

How to convert a string into an integer using the parseInt() function?

JavaScript has the ability to allow the programmer to create whatever they want. JavaScript allows you to write dynamic code to render the live changes dynamically. Converting a string is very common when you are developing an application, you have to deal with the different formats of the variable and therefore you need to handle every format using a specific method. This tutorial is going to help you to figure out how you can easily convert a string into a number.

 Approaches to convert a string into a number

There are many approaches to convert a string into a number., there are two methods that are being used to convert a string into a number: The first method is to parse a string into a number, While the other method is to convert the type of the string into a Number. In this article, we are going to learn how we can easily convert a string into a number with the JavaScript parseInt() method.

 JavaScript parseInt() method

This method returns the number after converting a string into an integer,. Let’s look at it practically that how the parseInt() method works and how we can use it to convert a specific numeric formatted string into a number. let number = parseInt("25"); console.log("The type is: ",typeof(number), "and the value is: ", number); Output As you can see, we have passed a string but the type of the string has been changed to a number and the value can now be used for any numeric operation.

 ParseInt() method with multiple arguments

The parseInt() method accepts many strings as its arguments but it only parses the first one into a number while it ignores all the other strings following the first one. Let’s take a look at the following example: let number = parseInt("30 50"); console.log("The type is: ",typeof(number), "and the value is: ", number); Output As I described above that parseInt() method only parses the first string while it ignores all the other strings following the first one, so here in the above example, you can clearly see that the “30” is parsed into a number while the 50 followed by the 30 is being ignored by the method.

 Passing extra spaces to ParseInt() method

The parseInt() method by default ignores all the spaces around the string and targets the strings exactly from where the exact string is being started. Let’s take a look at this in the following example, let number = parseInt(" 25 "); console.log("The type is: ",typeof(number), "and the value is: ", number); Output As you can see in the above example, the spaces are being ignored by the parseInt() method and producing the desired result.

 Passing alphabets to the parseInt() method

The parseInt() method will return a NaN as a result if you provide a string that is not in the numeric format. let number = parseInt("number"); console.log("The type is: ",typeof(number), "and the value is: ", number); Output As you can see above, when you pass the alphabetic string into the method, it parses its type into the number but because the string was not a numeric formatted string, it produces a result with NaN which means the provided format was not accepted by the method.

 Passing a float number to the parseInt() method

If you input a floating format string, just the first integer portion will be returned. let number = parseInt("25.99"); console.log("The type is: ",typeof(number), "and the value is: ", number); Output As you can see in the above output, the string after the floating point is ignored by the method and only the string before the floating point is parsed into the number.

 Passing comma separated multiple values to the parseInt() method

When you type a comma-separated text, just the first number is parsed and returned. let number = parseInt("25,99"); console.log("The type is: ",typeof(number), "and the value is: ", number); Output

 JavaScript radix method

The parseInt() method is not limited to converting the strings into the integer only but it can also be used to convert the strings into the desired base as well. All you need to do is just to provide the base when passing the string and that’s it for the method, the method is now responsible for converting that specific string into the provided base. The decimal number system typically employed by humans has a default value of ten. This parameter (10) should always be included to avoid reader misunderstanding and to ensure predictable behavior. The JavaScript radix method is also the same, which implies that it accepts the first argument as the string that has to be parsed into a number while the second argument is the base to which we want the method to convert the string to. Let’s take a look at the default base of the method first. Radix 10 – (Default) let number = parseInt("35”, 10); console.log("The type is: ",typeof(number), "and the value is: ", number); The above could return 35 which actually is defined as 3 x 10 + 5 = 35. Radix – 8 Let’s take another example, in which we want to parse the string into the octal numbers. We will pass 8 as the base number as shown in the code given below: let number = parseInt("56",8); console.log("The type is: ",typeof(number), "and the value is: ", number); The above code returns 46 which is actually calculated as = 5 x (8)1 + 6 x (8) = 5 x 8 + 6 x 1= 40 + 6= 46 Output Radix – 16 Let’s take another example with base-16 this time. let number = parseInt("56",16); console.log(number) Output

 Conclusion:

JavaScript uses many approaches to convert a numeric formatted string into a number, some of the major approaches that we have discussed in this article is the ParseInt() method which is used to convert the specific numeric formatted string into a number. The parseInt() method is not only restricted to converting the string into a number but this method is also capable of converting the string with the specific base as well. We have seen a couple of examples of both types where we converted the simple string into the integer and then we have looked at how we can specify the base with the string that we wanted to be converted to an integer format.

How to compare two dates

The date is a data type that is most widely used by software developers. Developers often encounter work with dates. You can easily create, store, or process data of date through JavaScript while developing applications. JavaScript has the built-in object of date which allows us the comparison between two dates., there are several methods for comparing dates. Now we will go over each method one by one. You can easily compare the current date with the previous and future dates. Numerous external packages like Moment.js are usually used by web developers for handling date-time operations. However, after the evolution of IT, JavaScript launched a new instance constructor known as Date for handling date-time operations.

 Creation of instance of Date

First of all, you need to create an object of Date. Date () constructor is used to create an object of date. We enlist the various ways to instantiate a Date. new Date () // current time and date will be returnednew Date (ms)new Date (stringdate)new Date(y,m,d,h,min,sec,ms) Where; ms= milliseconds, y = year, m = month, d = day, h = hour, min =minutes, and sec=seconds. Here the parameter of month starts from 0 to 11.

 Date comparison

In this article, we are presenting different ways to contrast dates.The simplest method to compare dates is by using the getTime() function.

 Compare Date through getTime() function

If you want to compare the date with time then you can use the built-in function getTime(). The getTime() function converts Date into numeric value. When values of Date are converted into numeric values then you can easily compare two dates. In this example, we use logical operators to compare two dates correspondingly. const instancedate1 = new Date("2021-01-31")const instancedate2 = new Date("2021-04-21")const instancedate3 = new Date("2021-01-31") console.log(instancedate1.getTime() > instancedate2.getTime()) console.log(instancedate1.getTime() < instancedate2.getTime()) console.log(instancedate1.getTime() === instancedate3.getTime()) console.log(instancedate1.getTime() !== instancedate3.getTime()) Output

 Compare Date with valueOf

There is another way to compare the Date by using the valueOf method. It will return milliseconds for a particular time span. The valueOf() function returns either true or false while comparing two dates. Example const instancedate1 = new Date("2021-01-31")const instancedate2 = new Date("2021-04-21")const instancedate3 = new Date("2021-01-31") console.log(instancedate1.valueOf() > instancedate2.valueOf()) console.log(instancedate1.valueOf() < instancedate2.valueOf()) console.log(instancedate1.valueOf() === instancedate3.valueOf()) console.log(instancedate1.valueOf() !== instancedate3.valueOf()) Output

 Compare Date using getMonth(), getDate(), and getFullYear() functions

JavaScript does not have the feature to compare Date without time directly. If you want to do this sort of comparison then you need to fetch month, year, and date from the objects individually. An example is enlisted below to contrast two dates by using built-in functions of JavaScript. function function_DateEqual(instancedate1, instancedate2) { return instancedate1.getFullYear() === instancedate2.getFullYear() && instancedate1.getMonth() === instancedate2.getMonth() && instancedate1.getDate() === instancedate2.getDate()} const instancedate1 = new Date("2020-02-31T09:11:12Z")const instancedate2 = new Date("2020-04-21T12:10:34Z")const instancedate3 = new Date("2020-02-31T03:34:23Z") console.log(function_DateEqual(instancedate1, instancedate3)) console.log(function_DateEqual(instancedate1, instancedate2)) Output

 Compare Date using toDateString() function

There is another method to compare Date without using time. You can use the toDateString() function for the comparison of dates by fetching only the date. instancedate1 = new Date(instancedate1.toDateString()) instancedate2 = new Date(instancedate2.toDateString()) instancedate3 = new Date(instancedate3.toDateString()) console.log(instancedate1.getTime() > instancedate2.getTime()) console.log(instancedate1.getTime() < instancedate2.getTime()) console.log(instancedate1.getTime() === instancedate3.getTime()) Output

 Compare Date by through date-fns

We should not rely only on JavaScript’s date object for the date comparison. Instead of using multiple methods for basic date comparison, it is better to use fewer lines of code to develop an efficient comparison of Dates without considering time. Date-fns is a third-party library for manipulation of date and its example is explained below by using different methods to confirm if the two dates are greater, lesser, or equal to each other. let instancedate1 = new Date("2020-02-30T05:11:12Z") let instancedate2 = new Date("2020-03-21T11:10:34Z") let instancedate3 = new Date("2020-02-30T09:11:12Z")//is instance date1 is written after the instance date2 console.log(datefns.isAfter(instancedate2, instancedate1))//is instance date1 is written before the instance date2 console.log(datefns.isAfter(instancedate3, instancedate1))//is instance date1 is equal to instance date2 console.log(datefns.isEqual(instancedate1, instancedate3)) console.log(datefns.isEqual(instancedate1, instancedate2)) Output

 Conclusion

We learned everything about how to compare Date along with an example in this article. We also explained several ways to compare Date. In the first method, we compare dates through the function of getTime() then we explore a method to compare dates through the valueOf() function. We also explored several built-in functions such as getMonth(), getDate(), and getFullYear() for the comparison of Date. Lastly, we also discussed another function toDateString() in order to compare dates. All these methods have been briefly explained along with examples of how Date functions can be used to compare the current date with the previous and future dates.

How to become a JavaScript Developer – Top 10 tips

During this current era of technology, it’s comparatively hard to choose which technology you are going with, especially when it comes to programming, you need to filter out your interests and get into the programming world by choosing a specific programming tool/language which will help you to pursue your interests. Technology has advanced in the modern world, making life simpler for both users and developers. JavaScript is a very handy tool when it comes to creating modern world applications (Single page Application/ Single-Threaded Applications). The race of learning modern JavaScript is growing up day by day hence you need to adopt the best ways to become a professional and efficient JavaScript Developer. This article will help you to decide the best road map to become a professional JavaScript Developer.

 Introduction to JavaScript?

JavaScript is a text-based computer language that can be used to create both client and server-side interactive web pages. While HTML and CSS provide web sites structure and style, JavaScript adds interactivity that keeps people engaged. If we take a look at the tools and technologies used in the past 10-15 years, because of having a multi-page web structure, it was causing a heavy load on the server as it reloaded complete information of the webpage whenever a server call was generated. Hence it was causing the webpage to be very time-consuming and resource hungry. But finally, there came a concept of Manipulating DOM (Document Object Model) which allowed us to keep all the data into the browser’s local storage once it got loaded from the server for the first time. And later on, whenever we needed any content update on the page we just needed to manipulate the DOM to modify the specific content without reloading the whole page. This concept was very useful and hence we finally got JavaScript to handle this process using its handy features to make our life easier. So now, the entire web is transforming into JavaScript-based technology. There are many JavaScript frameworks available in the market like React.js, AngularJS, Vue.js. Now the point here is how to learn these latest technologies faster. This article will allow you to decide the best road map and tips for learning JavaScript and you will learn how to become a full-stack JavaScript Developer. Let’s dive into it.

 Learning fundamentals of JavaScript

Like other languages, C, C#, C++, and Java, JavaScript has the fundamentals on which it is based. Basically, the fundamentals are the rules and methods on which a particular language is based on. No doubt you can’t learn full-stack web development as a matter of fact without learning JavaScript itself, yes you don’t need to be a master to get started with JavaScript, but you should have a basic understanding of JavaScript paradigms. Contrary to other technologies, JavaScript is not a very hard language to learn. It may look sloppy at the beginning but when it is used in a correct way, it is very handy and can do everything you want it to do. Objects and primitives are the two kinds of data whereas boolean, number, string, Null, and undefined are the five primitives. In JavaScript, everything else would be an object. JavaScript itself has evolved so much as at the beginning it was a simple language then vanilla features were added into it, that ES6 and ES7 came in and made our life easier by providing us with more reliable and shorthand functions. JQuery and Ajax introduced the concept of Asynchronous programming.

 Use Object-Oriented Approach

The object-oriented method is the most well-known programming approach today. Since its inception with C++, the object-oriented paradigm has exploded in popularity. Today, only object-oriented programming is used to create all of the main languages. An object-oriented strategy is one that is focused on a specific object. The object then becomes a fundamental entity. This object is then used to add attributes and functions to the page as a basis.

 Understanding DOM

When a page is loaded into a browser, the DOM (Document Object Model) is formed. This includes a number of levels that make it simple to access the various parts. With so many front-end frameworks and jQuery’s widespread usage, you would think that knowing the DOM is no longer necessary. On the contrary, I believe that understanding how the DOM works is critical to becoming a JavaScript master. JavaScript has the ability to modify any HTML element. It has the ability to alter your background color, font, and anything else. Knowing what will influence what is essential when JavaScript has enough power and is employed so widely inside HTML. As a programmer, you should understand how altering child and parent properties at the same time affects the page’s overall structure. For a JavaScript developer, the DOM is one of the most fundamental and crucial concepts, and he/she should be well-versed in it.

 Shifting on Frontend Frameworks

There are many frontend frameworks but the most popular ones are AngularJS, ReactJS, and VueJS. Due to speed advantages, one-page apps are the way to go nowadays. Learning a front-end framework is the most practical way to create one. The most popular are Angular, React, and Vue, although they aren’t the only ones. In the JavaScript world, there’s a race. If you Google “Angular versus React,” you’ll find a slew of articles comparing the benefits and drawbacks of each. Because of the given reasons, I prefer Angular. In some cases, React or Vue might be a nice option.

 Learn CSS frameworks for Stylings (Bootstrap 4)

You won’t have time to create all the necessary CSS code yourself to make your web app look nice whether it’s viewed on a regular desktop or a mobile device nowadays when virtually all web apps must look nice whether they’re accessed on a regular desktop or a mobile device. Many elements in front-end web development, such as popovers, pop-ups, navigation bars, notifications, and so on, may improve the user experience. If you try to add these features on your own, you’ll end up with a huge amount of boilerplate code that will take forever to create and maintain.

 Learning Backend Frameworks (Node.js, Express)

NodeJS is a programming environment that allows you to run JavaScript on the backend like any other programming language. There will, of course, be some small distinctions between JavaScript on the desktop and JavaScript on the browser. The V8 engine is used by both the browser and Node to execute JavaScript. The main distinction is that the browser offers an extra API for accessing the DOM, whereas Node adds an API for interacting with the operating system. You’ll need to know NodeJS if you want to do full-stack JavaScript. The nice thing is that you do not need to learn a new language from scratch. Express is then a complete framework that allows a rapid development process and makes life easier as it provides a complete backend utility where we don’t have to write the server-side code by ourselves as it provides on its own.

 Learning Typescript

JavaScript itself has uncountable issues in it such as.TypeScript generates ES5 code, which eliminates many of the compatibility concerns. I’ve enhanced my programming abilities and gained a better understanding of topics like interfaces, inheritance, access control (public, private, etc.), and abstraction by using TypeScript. If you come from an OO background, as I do, TypeScript will seem far more natural than plain JavaScript. Another advantage of TypeScript is that it may be used with a lint file to enforce code standards.

 Get your hands on MongoDB or any Relational DB

MongoDB is cross-platform document-oriented database software that is open source. MongoDB is a database developed by MongoDB Inc. and provided under the terms of the Server Side Public License. Traditional RDBs are replaced by NoSQL databases. Working with huge quantities of dispersed data is a breeze with NoSQL databases. MongoDB is a database management system that can store and retrieve document-oriented data. Using MongoDB along with Express makes the workflow speedy and more secure than a traditional node.js Applications

 Practice SQL

SQL (Structured Query Language) is a very handy tool that helps you to interact with relational databases. SQL is a powerful language that helps you to send and retrieve data from databases like Mysql, OracleDB, and PostgreSQL, etc. This will be another important paradigm of learning full-stack development as this will be frequently used in applications as this is the only tool that will help you to connect your running application with the database to send and retrieve data.

 Make your practices regularly

Accept as many problems as possible in addition to finding answers and creating websites. Challenges can take many forms, such as imagining a highly complicated feature on a website for practice. This will assist you in learning JavaScript at a higher level than others. You may need to learn a new library, a new idea, or both for that one feature, but it will undoubtedly benefit you in the future. So, constantly strive to come up with complicated ideas, and you’ll learn a lot more than you think.

 Conclusion

So, being a JavaScript developer is simple, becoming a JavaScript master is a little more challenging. It allows you to notice gorgeous components that do things you never dreamed of. The principles I mentioned above are crucial in becoming a JavaScript expert. Keep these in mind and implement them one by one. You are ready to compete with anyone and build anything (imagined or not) in the internet world once you have fulfilled the goals stated in each chapter.

Difference between Import and Require

JavaScript is a programming language that makes our website interactive by giving it the functionality of thinking and acting. When our web application development grows, we divide our code into multiple files(for debugging code easily and code reusability) which are called modules. Modules are just like JavaScript libraries, that contain a set of commands or functions that we can add to our application. To use these modules we take the help of Import and Require methods.

 What is require() method

Require is a built-in method of Node.js that is used to read and execute/include external modules in your current working file. When we call require() method in a JavaScript file, it reads the JavaScript file that is referenced and then executes that file. After executing, it returns the object that was exported. The require() method is used both for including built-in core modules or modules that we created locally in our application. Syntax const myModule = require("moduleName"); The require() method is used to reference the name of the JavaScript file/module (moduleName) that we want to include in our application. To include built-in modules like http we can simply follow the below code: const http = require("http"); To use a local module we pass the path of the module that we want to use in our application: var myModule = require('./myLocaModule');

 What is the import() method

The import() method was first introduced with ES6 modules and is used to refer to the ES6 module which we can use in our current working file. It should be noted that the import() method cannot be used outside ES modules; for example, we cannot import a file type of .json with the import() method. The import() method takes the URL style relative path or the package name that we want to import as its parameter. Syntax var myModule = import("moduleName");

 Difference between Import() and require() methods

The major difference between require and import method is that require method can be called anywhere in the JavaScript file and is non-lexical (wherever it is called it stays there) however, import cannot be called conditionally and is lexical (goes to the top of the current file and executed). Import() method is always executed at the top of the file. The next big difference between require and import methods is that when we use the require method, we have to save our javascript file with the .js extension, however when we use the import method then we have to go for the .mjs extension. From this difference, we can also see that one cannot use both the import and require methods in a single node program. The other difference between these two methods is that the import method loads the module partially hence saving memory whereas the require method doesn’t load partially.

 Conclusion

JavaScript is divided into modules/files for the purpose of easy debugging and code reusability. To call these external modules, inside the application or the page we use the import and require methods. In our application including local modules or built-in core modules of JavaScript is also achieved with require and import methods. In this post, we discussed what require and import methods are and the difference between require and import methods.

What is JavaScript? – Beginners Guide

For web developers, HTML and CSS were there to display content on the website and make it look aesthetically pleasing. But, they were unable to handle the interactivity of the web pages. For this purpose, another language was required, specifically to handle the programming aspect of your website. So that it could handle your website’s dynamic and interactive behavior. Hence came JavaScript. It’s one of the most popular scripting languages that work on the client-side to handle the interactivity of your web page. Furthermore, it can increase the dynamic behavior of the website by manipulating the content it receives from the web server. There is a whole bunch of stuff that JavaScript can do, we’ll learn it in this article along with how it works and some basic concepts.

 Various Functions that You Can Do With JavaScript:

Modify web page content by adding and removing the elements. Monitor various mouse clicks, hover events and handle their actions. Control various animations and transitions. Event handling when a user enters some input. Validate the input that the user provides before submitting to the server. And so many more, You can control how your page behaves.

 Why learn JavaScript?

JavaScript was considered to be a tool only for interactive web pages. But those days are gone, and now you can build full mobile and web applications as well as networking applications using various frameworks provided by JavaScript. You can also design browser games with JavaScript. It is out-growing other languages and famous companies are building their applications around JavaScript. Now, you know the importance of learning JavaScript so let’s see how it works.

 JavaScript Code Editor

For JavaScript code, you can use the browser’s console or even online JS editors. But, it’s best to use code editors. There are various code editors out there like Visual Studio Code, Sublime Text, Atom, and more You can check various JavaScript editors available through this article. Out of these, Visual Studio Code is highly recommended as it is the most commonly used Code Editor, and the reasoning behind that is its constant support for upcoming technologies and Easy-to-use User interface.

 How to add JavaScript to your file?

There are two ways of adding JavaScript to your HTML file: Internal Script (Configuring JavaScript inside HTML file using <script></script>tag) <script> let con; con = Boolean(''); console.log(con) </script> External Script (Creating a seperate file for JS code and adding the link in the tag <script src =?></script> <script src = bundle.js> </script>

 consol.log, alerts, and document.write

A useful command to debug and log your code is console.log. It’s useful indirectly writing content in the web console. console.log("Hello World"); Alerts are used to provide alerts to the end-user who is accessing the web page. alert("Hello World"); Document.write modifies the content on the web page by adding additional content to your web page. document.write("Welcome to the Web Page!"); In JavaScript, the console has a bunch of methods. More in-detail information is here.

 How to add comments

While programming, writing comments are extremely useful. It helps you remember what you coded and if there is any extra information you need to write for the other person who’s checking your code. Both single and multiple line comments can be written. To use a single-line comment in code (JavaScript) we use //: // This whole sentence is one big single-line comment. Whereas, in the case of multiple line comment use /* in the begging and close it using */: /* This is a multi-line comment. You can even your blog here if you want to.*/

 Variables

Just like in any other programming language, variables are also used. The job of a variable is to hold a data type in a named reference. we can set variables using three ways: var, let, const. The var is used since the beginning of JavaScript and it’s globally scoped, which means that all the functions on that page, or in that program can access it. var x = 15;var y = 4; console.log(x + y); Output: Because it is globally scoped, it’s better to use let and const. The reason is that sometimes you want to declare a variable in an if statement, and outside that if statement you want to declare the variable with the same name. Using var will cause problems. To understand more about global variables, you can check this article. The Remaining two types of variables that are available are let and const. Using let we can declare any data type, whereas, in the case of const, only constant values are declared. let msg= "Hello World"; console.log(msg); msg= 10; console.log(msg); Output: Here, we declared a string as well as a number data type using the let variable. Now, using const, if we try to declare any value other than constant, it’ll give us an error. // Below will cause an error.const pi = 3.142; console.log(pi); pi = 3.15; console.log(pi);

 Data Types

JavaScript provides us with various data types such as Numbers, Strings, Booleans, Float, Objects, and more. If you want to read about the Data Types then you can head over to the official MDN Docs. It tells the program what type of data they’re working with and manipulating. Number: The data type to represent a positive, negative integer or floating-point is Number. let num = 11; console.log(num); console.log(typeof num); num = -12; console.log(num); console.log(typeof num); Output: String: To store a sequence of characters, the String data type is used. let x = "Welcome" console.log(x); console.log(typeof x); Output: Boolean: A data type that represents true and false values in a program. let x = true console.log(x); console.log(typeof x); Output: Objects: To store the collection of various data types in a single variable, Objects are used. let movie = { name : "Inception", genre: "Thriller", yearOfRelease : "2010", numberOfCopies : 10 }; console.log(movie); console.log(type of movie); Output:

 Arrays

To store the collection of data of any type we can use Arrays. Simply initialize the array using the array constructor: let months = new Array(); Or with [ ] initialization: let months = []; Or simply create an Array with explicit data: let months = ["January", "February", "March", "April", "May"]; The index in Array starts with zero, and to access any element you simply have to write array[indexPosition]: let months = ["January", "February", "March", "April", "May"]; console.log(months[3]); Output: To better understand the Array concept, check this article.

 Methods for Different Data Types

Various methods are out there to manipulate the values of various data types. String Methods: To modify the values of a String, there are numerous different methods available to us. These can be used to check the length of a string, find the position of a certain word in a string or convert it into different data types. let x = "Hello, Welcome Home"//To check string length console.log(x.length);//To cut a specific part of string console.log(x.slice(3, 7));//To replace a specific word in a string console.log(x.replace("Home","Here"));//To convert string to Lowercase letters console.log(x.toLowerCase()); Output: Of Course, there are several other methods, if you want to learn more check this article as well. Number Methods: Similarly for manipulating the value of a Number data type, there are various methods. Some of these are provided below: let x = 4445.4//To convert numbers to a string console.log(x.toString);//To convert number to its exponential form console.log(x.toExponential());//Returns the number with specified length console.log(x.toPrecision(2)); Output: Javascript provides us with methods for objects, boolean, arrays, and more.

 Conditions

Another fundamental part of programming is to make decisions and cause some actions based on these decisions. This can be done through conditional statements. You can use: If..else: let balance = 1200;if(balance < 1000){ console.log("Balance less than 1000");}else{ console.log("Balance more than 1000");} Output: If.. else if…else: let balance = 1200;if(balance <1000){ console.log("Balance less than 1000"); }else if(balance >1000 && balance <1500){ console.log("Balance between 1000-1500"); }else { console.log("Balance more than 1500"); } Output: Switch: let alphabet = 'B';switch(alphabet){ case 'A': console.log("Egg"); break; case 'B': console.log("Mango"); break; default: console.log("Tea!");} Output: To understand the topic better you can check these articles of if-else and switch conditional statements in detail.

 Loops

Until a certain condition is met. Loops keep repeating a chunk of code (could be a single-line and even multiple-line) JavaScript provides for, while, do-while, and for each loop. Here is how they work along with examples:

 For Loop

It loops through a given code several times. for(let i=0; i < 10; i++){ console.log(i + " ");} Output: You can understand the concept and work of this through this article.

 While Loop

Loops through a specified given code until the given conditions are met. let i = 0; while( i <4 ){ console.log(i + " "); i++;} Output:

 Do While Loop

Similar to the while loop, there is a do-while loop. It differs in this aspect that here at least the loop will be executed once. The reason is that the conditions are checked at the end of the loop. let i = 0;do{ console.log(i + " "); i++;}while(i < 3); Output: Output:

 For Each Loop

To iterate over a collection like Arrays, for each loop is used. let letter = ["m", "a", "n", "g", "o"]; letter.forEach( function(entry) { console.log(entry + " "); }); Output: This is just to give you a basic understanding. If you want to understand this in-depth, check this article, or to understand the for-in loop you can check this article as well.

 Functions

Functions are blocks of code that are assigned to perform some task. For example, you want a message to display when you click a button. So this will happen through the use of functions. To understand the concept in detail you can check this article. Here’s a demonstration of how it works: function addition(i, j=5){ return i + j;} let result = addition(3,5); console.log("add(3,5) is " + result); Output: In the above example, two numbers were passed into the function of addition() and were stored in the variable result. JavaScript provides us with various data types, functions, methods, and more in-depth. These are extremely useful and make the understanding of the program easy. There are so many ways you can learn JavaScript, Through books, as well as through online resources.

 Conclusion:

In today’s guide, we learned the basics of JavaScript. JavaScript has become nothing less than essential for interactive, and attractive web pages. Nowadays, JavaScript provides us with various frameworks that even help us in developing web and mobile applications. Developers are also creating browser games using JavaScript. With the increase in demand for JavaScript, the resources to learn the language are also increasing. You can learn it through online tutorials, courses, or even through books. But, no matter what your medium of learning is, the only thing that makes you an expert is practicing.

What is the “in” operator?

Whenever you are dealing with JavaScript objects or dictionaries, you will always have to deal with searching out the specific records from that object or collection. Sometimes, you will need to access the specific attribute and use it somewhere to display them on the UI or on the frontend side. Hence we are using JavaScript so it became so easy to achieve this functionality as JavaScript provides us with the ‘’in’’ operator which is quite helpful in this and we can achieve the same functionality just by using this “in” operator wherever we want this in our JavaScript code. Let’s take a deep look at how this operator works and how we can easily use it to get the specific values or attributes from an array or object.

 What is the object of ‘’in’’ operator?

The in operator is a Utility Operator that is used to check if a property or an attribute is existing on the specific array or a JavaScript object or not. Its response is boolean which means that It will be returning true if the search was successful and an element was found in the object otherwise it is going to return false if that specific element does not exist in the collection. Here in this write-up, we are going to look at how the ‘in’ operator works and how we can easily utilize this operator to test out our required functionality. In this tutorial, we assume that you have a basic understanding of what exactly the JavaScript objects are and how we can easily create our own objects and basic knowledge of how the inheritance works. Because, the “in” operator also helps us in finding some method or object in some class. We will cover some basics in the following procedure but we still recommend having a knowledge of inheritance to understand the further concepts “in” operator.

 When should you use ‘in’ Operator?

JavaScript ‘’in’’ operator can also be used to check if there is a function or a method attached to the instance of some class, which means that whenever you are required to check such cases, you are opted to use the “in” operator approach as it is a prototype chain and can easily provide you the required results. The JavaScript prototype chain is how objects and object instances get access to attributes and functions that aren’t their own. The __proto__ property allows you to access properties and methods defined in the constructors or prototypes of these objects. Let’s take an example of how the in operator works in the code and how we can easily use it in our code to have the desired functionality. Example To determine whether an item has a given attribute or not. const person = { name: 'johndoe', age: 21, phone: '123456789', start: () =>{ console.log(`Name ${this.name}, age ${this.age} and phone is ${this.phone}`); }} console.log('name' in person) console.log('start' in person) console.log('johndoe' in person) Here in the above code, we have simply created a person array which contains some properties like name, age, phone, and a method that logs out a message with some person’s information on the terminal. Later, we have checked out some of the properties that if they are existing on the object by using the in operator. The first console will return true as the name is a property that exists on the above person object while the start is also a property in person object. But the last console.log is not going to return true instead it is going to return false as the johndoe is not a property in the person object, it is the value against the name property in the object hence this is the reason that it is not going to return true for johndoe. You can take a look at the below output screen for verification as well. Output

 JavaScript in operator to check whether the Array is using a key or the index for its values

JavaScript’s “in” operator can also work with arrays as well. Until now we have discussed it and implemented the example with the objects but it behaves almost the same with the arrays as well., the array is the prototype or the instance of an object or in other words, you can consider everything as the instance of the Object. That might sound weird, but let’s test it with a simple application in the browser’s console. Example To begin, create an array and use the instanceof operator to see if it is an instance of the Object type: const array = [1, 2, 3, 4]; console.log(array instanceof Object) // Returns true Here in the above example, we have created an array, and then later on in the console.log we checked if that is the instance of the object or not. Take a look at it in the following output Output: A set of attributes will appear, one of which is __proto__, which links to Array. We can also open it and proceed through the list until we find another __proto__ property with the value Object. Now let’s return to the in operator again and test this operator with the JavaScript array: const array = [1, 2, 3, 4]; console.log('Yes 3 is in the array :',3 in array) console.log('Yes 2 is in the array :',2 in array) console.log('filter' in array) Here in the above code we have created an array with the values 1,2,3 and 4 and tested the values using in operator whether they are existing in the array or not. Output Afterwards, we got all the responses true and printed on the output screen because all the values that we are checking are existing on the array collection.

 Conclusion:

JavaScript’s “in” operator is used to check if a particular property exists in an object or not. The ‘’in’’ operator responds with a boolean value which means that it returns true if the value exists in the object and false if that particular value is not present. In this article, we have seen the working of in operator on both the objects and arrays and discussed some of its examples in detail.

What is a Map Object?

JavaScript is a programming language that gives web applications and web pages the ability to think and act by making them dynamic and interactive. When you are programming, it would often confuse you with which data structure to use for storing data that can easily be managed and understood. To hold collections of data, arrays and objects are commonly used data structures. Key-value pairs are stored in objects, while indexed lists are stored in arrays. Then came the ECMAScript 2015 which introduced another iterable object known as maps to provide developers more flexibility. So, in this post, we will discuss what a map object is and discuss some practical examples along with screenshots of the output.

 What is a map object?

Map object like an ordinary object is a collection of elements that stores key-value pairs; however, the main difference is that the keys can be of any type. It should also be noted that the map object remembers the order of the key-value pair that was inserted in the map object. Syntax: var map = new Map([it]); Where it is optional and an iterable object whose elements are stored as key-value pairs. Map object has some properties and methods which are defined below: For creation of new map -> new Map() To store a value using a key -> map.set(key, value) To get the value of the key -> map.get(key) If the key doesn’t exist then map.get(key) will return undefined To remove everything from the map -> map.clear() To get the size of the map -> map.size To delete a value using the key -> map.delete(key)

 Map Object Example1

In the code given below, first, we initiated the map object and then set the values. The first key that we set is a string key, the second is a numeric key and the third is a boolean key. Then we console log the result of getting the values of the keys provided. We also check the size of the map object which returns 3. // map creationvar map = new Map();// setting key value pairs to map map.set('1', 'string'); // a string key map.set(1, 'number'); // a numeric key map.set(true, 'boolean'); // a boolean key//get info from map console.log( map.get(1) ); // number console.log( map.get('1') ); // string console.log(map.size); // 3

 Map Object Example2

We can also set the keys of the map object as objects. Let us demonstrate this with the help of the below-given code: var student1 = { name: "Jhon" };// for every student, let's store their marksvar marks = new Map();// student1 is the key for the map and student 1 itself is an object marks.set(student1, 93); console.log( marks.get(student1) ); // 93 In the above example, we first initiated an object with the name of student1 and then created a map object. After that, we set the marks of student1 and then console log the marks of student1. It should be noted that student1 itself is an object but acts as the key here. We get the output 93 as shown below:

 Iterating over map keys

Let us now see how to iterate over map keys for which purpose we will use a for loop and map.keys() method. The map.keys() method will return all the keys of the map object in the order they were inserted in the map object. Let us initiate a map object and give names as keys and values as the job position. Then we implemented a for loop that will console log all the keys/names in the map object. // creating map objectvar employees = new Map([ ["john", 'admin'], ["Sarah", 'editor'], ["Sam", 'writer']]);// for loopfor (var name of employees.keys()) { console.log(name);} The output of the above code is: To iterate over map values, we will simply change employees.keys() to employees.values(): // creating map objectvar employees = new Map([ ["john", 'admin'], ["Sarah", 'editor'], ["Sam", 'writer']]);// for loopfor (var position of employees.values()) { console.log(position);}

 Deleting Element using Key

In this example we will delete an entry in the map object using the delete() method: // creating map objectvar employees = new Map([ ["john", 'admin'], ["Sarah", 'editor'], ["Sam", 'writer']]);// deleting john from employees employees.delete("john");// for loopfor (var name of employees.keys()) { console.log(name);} We can see that John has been deleted and missing from the output:

 Conclusion

Map object was introduced in ES6 and prior to map object, ordinary objects were used. However, an object has some deficiencies like an object always has a default key prototype and one cannot use an object as a key. To solve this problem, the map was introduced which is a collection of elements stored in key-value pairs just like objects but here keys can be of any type. In this post, we saw a map object and discussed two examples. Apart from that, we also implemented and looked at different methods and properties of map objects of JavaScript.

What is the yield* keyword/expression?

Yield is a keyword/expression that is used to halt the implementation of the generator function. A generator function is similar to other functions but they are different in such a way that the value returned in the generator function is the yield keyword. Nested functions or callbacks cannot allow yield expressions. Two characteristics are observed in objects returned by yield expressions, value, and done, which are the actual value and Boolean value respectively. When the generator function is fully done, then the Boolean value is returned true and vice versa. If the yield expression is being paused then it will pause the generator function too and it will only restart when the next method is being called until another return expression. The syntax of yield expression/keyword is as follows: function* name(arguments) {statements} Where name represents the name of the function, arguments are the parameters being passed for the function and statements represent the body of the function. Following are the features of yield* expression/keywords: Memory efficient Lazy evaluation Control flows asynchronously Now we are going to illustrate an example through which you can easily understand how to use yield* keyword/expression. function* showNum(x) { while (x > 0) { yield x--; }} //instance is created for function showNumconst generator_val = showNum(4); //return 4 as 4 is passed to the function showNum yield expression console.log(generator_val.next().value);// return 3 console.log(generator_val.next().value);//return 2 console.log(generator_val.next().value);//return 1 console.log(generator_val.next().value); Output On the other hand, the yield* is a keyword/expression that can be used to represent an iterative object or other generator function. The yield* iterates and returns value correspondingly until the Boolean value is true. The syntax of yield* expression/keyword is as follows: yield* expression Now we are going to present an example of yield* expression/keyword. <html><head> <title>JavaScript yield* keyword/expression</title></head><body> <script> function* first_func() { yield 10; } function* second_func() { yield* first_func(); } const generator_iterator = second_func(); console.log(generator_iterator.next().value); </script></body></html> Output Example In this example, generatorfunc1() function returns yielded values through next() function similar to those values that are yielded through generatorfunc2() function. Subsequently, through this generatorfunc2() function, we can easily insert more generators as much as we can. <html><head> <title>JavaScript yield* representing other generator </title></head><body> <script> function* generatorfunc1() { yield 22; yield 33; yield 44; } function* generatorfunc2() { yield 11; yield* generatorfunc1(); yield 55; } const iterative_value = generatorfunc2(); // it return value 11 whereas done i.e. boolean value is false console.log(iterative_value.next()); // it return value 22 whereas done i.e. boolean value is false console.log(iterative_value.next()); // it return value 33 whereas done i.e. boolean value is false console.log(iterative_value.next()); // it return value 44 whereas done i.e. boolean value is false console.log(iterative_value.next()); // it return value 55 whereas done i.e. boolean value is false console.log(iterative_value.next()); // it return undefined value whereas done i.e. boolean value is true console.log(iterative_value.next()); </script></body></html> Output

 Conclusion

After reading this article, you are familiar with the yield* keyword/expression. If you are using the yield* expression then you cannot face the callback issues. The concept behind yield* expression is that function can voluntarily resume or stop till it acquires what it needs. We also enlisted examples that help you to understand the better usage of yield* expression/keyword.

What is the difference between JavaScript and HTML?

Both JavaScript and HTML are the required web technologies languages used to create a fully functional web application or webpage. HTML first version was introduced in 1993 and it simply displayed plain text on a webpage. JavaScript was invented in 1995 to give more flexibility and add functionality to web pages. In this post, we will discuss both JavaScript and HTML along with answering the question of what is the difference between JavaScript and HTML.

 HTML

HTML is a hypertext markup language that gives our web pages structure and allows us to display plain text. Every web developer knows HTML and it’s the first step that a beginner developer takes to learn web development. HTML has elements, also called tags, that tell our browser how to display the content of our webpage. Let us view a simple HTML webpage: <!DOCTYPE html><html lang="en"><head> <title>Document</title></head><body> <h1>Heading</h1> <p>Simple Webpage in HTML</p></body></html> The output of this code will look like the following:

 JavaScript

JavaScript is a proper high-level programming language that gives our web applications and web pages the ability to think and act by making them interactive and dynamic. JavaScript is used for validation, manipulation, and calculation of data and the best thing about JavaScript is that it can be used on the server-side as well as the client-side. One common example of JavaScript usage will be the Amazon Search bar where you search for an item and the item is displayed. This functionality is programmed. To put it simply, JavaScript improves the user interface of the webpage and makes a web page interactive hence enhancing user experience. A simple example of JavaScript is given below where are initializing a variable and then we console log that variable:

 Difference between JavaScript and HTML

HTML gives structure to our webpage whereas JavaScript makes our webpage dynamic and interactive. HTML is a markup language whereas JavaScript is an advanced programming language. HTML uses tags like <h1>and <p>to define or manipulate text which is limited whereas JavaScript offers inbuilt functions where we can manipulate and define data. HTML works on all browsers whereas JavaScript is not compatible on all browsers and when the version changes as well as it requires a JavaScript engine to run the javaScript code. HTML shows the same content to every user and cannot interact with the user whereas JavaScript can show content to a certain user and can interact with the user. HTML static material is shown on the server-side, whereas JavaScript programs are performed on the web browser’s client-side. HTML allows embedding of JavaScript within however JavaScript doesn’t allow HTML embedding within. HTML is maintained by W3C and WHATWG whereas in the JavaScript case, it is maintained by the ECMA TC-39 committee. HTML contains no supporting libraries to further improve the appearance of the webpage whereas JavaScript has various libraries like React js, Angular js which add more functionality to improve our web application or webpage.

 Conclusion

HTML is a hypertext markup language that is older than JavaScript and plays with the manipulation of plain text and provides static structure to our webpage. JavaScript is an advanced web programming language that makes our web applications and web pages dynamic and interactive. To put it simply, HTML specifies how a web page should appear, whereas JavaScript enables you to interact with web pages. In this post, first, we defined what HTML and JavaScript are and then went on to answer the question of what the difference between HTML and JavaScript is.

What is the difference between Pass by Value and Pass by Reference?

JavaScript is a programming language that gives our web applications and web pages the ability to think and act by making it interactive and dynamic. Like any other programming language, JavaScript offers us functions which are a set of defined commands or statements that are executed only when we call the function that has this code. The function takes an input or some arguments and returns the output. The input arguments can be passed by value or reference. So, in this post, we’ll define the terms “pass by value” and “pass by reference” along with examples, as well as explain the differences between the two.

 What is pass-by-value?

A function is called directly by sending the value of the variable as an argument if that function is pass-by-value. As a result, any changes made within the function have no impact on the initial or original value. The original value isn’t changed because when we pass the variable into a function as an argument, the copy of that variable is created and hence any changes or operations performed inside that function are done on the copy variable rather than the original one.

 Pass by value Example

Let us create a function with the name of passByValue and change the values of the variables a and b that are passed as arguments in this function. Outside the function, we initialize the a and b variables and give them 1 and 2 values respectively. Then we console log these values. function passByValue(a, b) { a=3; b=4; console.log("Inside the function") console.log("a: ",a, " b: ",b); // 3, 4} let a = 1; let b = 2; console.log("Outside Function. Before calling function"); console.log("a: ",a, " b: ",b); // 1,2 passByValue(a, b); console.log("Outside Function. After calling function"); console.log("a: ",a, " b: ",b); // 1,2 We will see that when we console log the values of a and b outside the function it will say 1 and 2. However, inside the function, the values will be 3 and 4 and again after calling this function the values won’t change as inside the function copies were made of a and b and changes were made to those copies.

 What is pass-by-reference?

A function is called by supplying the variable’s reference/address as a parameter in pass-by reference. As a result, modifying the value within the function also modifies the value outside the function that is the original value. The pass-by-reference feature is used arrays and objects.

 Pass by Reference Example

Let us initialize an object and give two properties to it. One property defines the name of the machine and the other “isOn” which lets us know whether the machine is on or not. We also initialize a function with the name of passByReference and change the value of the computer object properties like name and isOn. We then console log these properties before and after calling the function: function passByReference(machine) { machine.name="Computer"; machine.isOn = true;}var computer = { name: "myComputer", isOn: false}; console.log("Before calling function"); console.log(computer.isOn); // true; console.log(computer.name); // Computer passByReference(computer); console.log("After calling function"); console.log(computer.isOn); // true; console.log(computer.name); // Computer We can see that copies weren’t made in the function and the original properties of the computer object were changed, hence it is passed by reference.

 Difference Between pass by value and pass by reference

The major difference between pass by value and pass by reference is that pass by reference comes into play when we assign primitives and pass by value comes into play when we assign objects. Primitive data types include string numbers, boolean, symbols, and values like null and undefined, and the object data types include functions, arrays, and simple objects. The second major difference between the two is that pass-by-value creates a copy and then changes are made to that copy; however in pass-by-reference no copy is made and modification is done on the original variable.

 Conclusion

We can pass values into a function via pass by value or pass by reference. Pass by value is done on the primitive data types like string, number, boolean, and every time you pass a variable to a function, it creates a copy of that variable and then modifies that copy in a pass by value. Pass by reference is done on the object data type like functions, arrays, and plain objects, and in the pass by reference, the original value is modified as pass by reference doesn’t create a copy. In this post, first, we saw what pass by value is and pass by reference is and explained both the phenomena with the help of an example and then continued our discussion by answering the question of what is the difference between pass by value and pass by reference.

What is the Window onload event?

With the new advancements in web development, JavaScript is even evolving in different frameworks, which makes life easy for developers. Talking about its use, as of now many famous websites are built on JavaScript which depicts how reliable this language is. JavaScript has a window onload event to launch certain functions whenever a web page is loaded. The onload event is also used for verification of type and version of visitor’s browser. Further cookies can also be checked through the onload attribute. The attribute of onload triggers when the object is loaded in HTML. This is to launch the script whenever the associated element loads. In simpler words, we can say that the window onload event is triggered whenever a web page is launched successfully. Onload event is used with to run a script once its substance (which includes CSS files, images, and scripts) of the page is triggered completely. However, you do not always need a tag. It can be used with other Html elements. The download.onload launches before the images and external contents, triggered just before the window.onload. Whereas, window.onload starts after the page is completely loaded including CSS, script files, images, and many more. If you want to manipulate load event, then you need to register event listener through method of addEventListener() as shown in the example below: window.addEventListener('load', (event) =>{ console.log(Page Loaded);}); You can also handle the load event through the property of the window object i.e. onload. The example below shows how to use onload property: window.onload = (event) =>{ console.log('Page Loaded');};

 Window.onload Event in the head section of HTML

First of all, we are going to present a simple example of a window.onload event. In this example, we simply display an alert message whenever a page is loaded. Syntax window.onload= functionName(); Example <html><head><script type="text/javascript">function js_onload_code (){ alert(" Hello, you are learning onload event");} window.onload= js_onload_code ();</script></head><body ></body></html> Output

 Onload Event in the body section of HTML

Content can be displayed in the body section of HTML. Whenever the webpage is loaded then the event which occurred at that time is named onload event. We can use the onload event in the body section so that we can execute the script. Syntax <body onload="functionname()";> Example If you want to use an onload event within the body section then run the following code. <html><head><script type="text/javascript">function js_onload_code (){ alert(" Hello, you are learning onload event");}</script></head><body onLoad="js_onload_code ()";></body></html> Output

 Window Onload Event in the body section of HTML

The object of the onload window represents the window of the browser. Whenever all the operations are completely loaded then onload property processes the load event. The function which we want to execute is allocated to the handler function of the onload property. Whenever the webpage gets loaded then the function will be executed. We have provided you with an example below. Syntax window.onload = function functionName() { // write function here} Example <!DOCTYPE html><html><head> <title> Window Onload Event </title></head><body> <b>What is window onload event?</b> <p>Script Executed. Now you can check your console to see the output. </p> <script> window.onload = function your_function_name() { console.log('Hey, you are learning window onload event. Script will be loaded.'); } </script></body></html> Output

 Output of Console

If you want to see the output of the console then you have to open devTool by pressing the shortcut keys i.e. CTRL+SHIFT+ I. After opening the Devtool, you will be able to see the console’s output screen as shown below.

 Conclusion

We have learned about what window.onload() event is and also learned the syntax of onload event. We briefly discussed several methods of how to write onload events along with an example. To recap, window.onload() event triggers after the web page has been loaded. We also see that the onload event is useful to set the version of browsers and also used to observe the cookies of a web page.

Working with Phone Numbers code

One of the major problems that developers face in their early development is how to take data from a user and then validate that data. If you are taking an input like a name or registration number from a user then you can easily validate that data, however, it becomes a little complex when you are taking input as a phone number. In this post, we will go through how to take a phone number as input from a user and then validate it according to our needs in this post using the HTML5 input tag with tel type and then using a simple input tag of HTML and validating it ourselves using JavaScript.

 Using HTML5 input tag with tel type

We can use the HTML5 input tag to take input from the user and we can give the type of tel in the input tag to tell the browser that this input box should take a phone number. The HTML5 input tel type has some advantages one being that we can set the required attribute in the input tag telling the browser that the user cannot proceed without entering the phone number and the other is that we can set a pattern attribute. Let us demonstrate the input tag in HTML: <input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required> In the above code we can see that we have given a regular expression as a pattern to the input tag and hence using this will validate the phone number. Let’s view a proper HTML program: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <form id="myform" action="javascript:void(0)"> <label for="myform_phone">Example: 123-456-7890</label> <input type="tel" id="myform_phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="Enter Phone Number"/> <button type="submit">Submit</button> </form></body></html> In the above code, we initialized the label tag which shows an example of the phone number that is accepted by the below input tag where we have defined a pattern. Now the input tag itself will be responsible for validating the input taken from the user. After this, we defined a button and gave it the type of button. Whenever a user will click on the submit button it will generate a response based on the form tag action. Some of the examples are below: If we click on the submit button leaving the phone number input box blank: If we give a wrong pattern and click on the submit button we will see the following warning:

 Using JavaScript to validate Phone Number

We can also validate the phone number using JavaScript. For this first we will create an input tag and a button in HTML in the following manner: <!DOCTYPE html><html lang="en"><head> <title>Document</title></head><body> <label for="myPhone">Example: 123-456-7890</label> <input type="tel" id="myPhone" placeholder="Enter Phone Number"> <button onclick="handleClick()">Submit</button> <script src="code.js"></script></body></html> We used the onclick event on the button element which means whenever a user clicks on the submit button, the handleClick() function will start executing. This handleClick() function will be initialized in a separate file code.js which we referenced using the script tag seen in the above code. Let us now work on the JavaScript part: // function to handle click on submit buttonconst handleClick=()=>{ // getting the reference of myPhone input var input = document.getElementById("myPhone").value; // format for the phone number var format = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/; // conditional statements if(input===''){ alert("Please Enter Phone Number") } else if(input.match(format)){ alert("Phone Number: "+ input); } else{ alert("Type using correct format"); }} In the above code, first, we initialized the handleClick() function and then we reference the value of the input tag. After that, we define the format of the phone number that we want using regular expressions. An accepted phone number example, in this case, would be 123-456-7890. Next, we use the conditional statements and we check that if the input is empty then alert Please Enter Phone Number else if the input matches the format then alert that number otherwise alert that the number the user has types is in the wrong format. Let us view the output one by one: First, we will click on the submit button while leaving the input box blank: Next, we will type a wrong format number, then we will see the following output: In the end, let us go for the correct format and see the output:

 Conclusion

Validating phone numbers can become a headache for a new developer. There are two methods that we can use to validate phone numbers. First, to take input from a user with the help of an HTML input tag. Next to validate the phone number we give the input tag the type of tel and a pattern to which it should validate. The second method is making a custom JavaScript program that will validate your phone number according to a given format given as a regular expression. In this post, we learned how to take a phone number as an input from a user and then we validated that phone number using two methods; HTML5 input tag with tel type and custom JavaScript logic.

Yarn Introduction and Tutorial

Yarn is an abbreviation of “Yet Another Resource Negotiator” and is a package manager of various software programs. The best thing about yarn is that it permits you to share and utilize code securely and rapidly among distinct developers all around the globe. If you want to create your own software and you are facing difficulty in it then Yarn will help you to use the solution of other developers. When you are using Yarn and there is an existing issue in it then we will report it and when the issue is resolved then you can again use the updated yarn. Module or package is the means to share a code. The package consists of a code along with all its description in the “package.json” file. Yarn is considered more efficient and effective than java as it allows other applications including spark to run on the yarn package. Applications of yarn could simultaneously work together in a similar cluster. The four major components of Yarn is enlisted below:
    Client: Responsible for submitting MapReduce. Resource Manager: Responsible for the resources management within the cluster. Node manager: Responsible for introducing and monitoring computing containers within the cluster. Map-reduce application master: Responsible for checking all the running tasks. Application-master works within the containers and resource manager and node managers are responsible to schedule it.
If you want to use yarn then you must need to install it on your machines. You can install yarn in several ways.

 Yarn architecture

First of all, the client sends an application to the resource manager. Then the resource manager has the ability to reserve the container to launch the application manager. Subsequently, the application manager now works with the containers of the resource manager and sends a notification to the node manager. Then the node manager starts the application. Execution of application code is done within the container. The client gets the status of applications either through the resource manager or application manager. When the process is finished the application manager unsubscribes itself from the resource manager. The illustration of yarn architecture is shown below.

 Yarn installation through npm

Npm package manager is highly recommended for yarn installation. When you installed npm on your machines then execute the following command in the terminal to install an updated version of Yarn. npm install --global yarn

 Example

 Alternative methods to download Yarn

If you want to install Yarn through Chocolatey then first you need to install chocolatey. You can easily download this package manager from its official website. When you successfully installed chocolatey package manager on your machines. Then check your machine whether node.js is installed already or not. If not, then visit this link https://nodejs.org/en/ and download from there. Subsequently, execute the following command in the terminal: choco install yarn Furthermore, you can also install Yarn through Scoop. You can easily download this package from its website. When you successfully installed Scoop on your machines then run the below-mentioned command. scoop install yarn Scoop checks itself whether node.js is downloaded on your system or not. If not, then it offers you to download it efficiently by using a single command as shown below: scoop install nodejs There is an alternative method to download yarn for Linux which have the below-mentioned command: sudo emerge --ask sys-apps/yarn Now we are going to briefly explain some of the common Yarn commands further in the same article.

 1.Check Version of Yarn

You can check the version of Yarn in few seconds by using this command as mentioned below: yarn --version

 2.Update Version of Yarn

If you want to update the version of Yarn then execute the following command. yarn set version latest

 3.Make New Project

Run the below-mentioned command to create a new project. yarn init Whenever you execute the above-mentioned command you have to answer all the questions like the name of the project, version, description of the project, etc then press enter. Now you successfully created your project.

 Output

 4. Install Dependencies

By using this command, you can easily download all dependencies. yarn yarn install

 Example

 5.Add Dependencies

Run the following command as mentioned below to switch your package. For this, you have to add the package as a dependency. yarn add [package] yarn add [package]@[version] yarn add [package]@[tag] When we use these commands then it will automatically add dependencies in the package.json file and it will also modify yarn.lock file accordingly.

 Example

In this example, we specify which version of the package we are going to download.

 Output

 6.Upgrade Dependencies

By using these commands you will easily upgrade dependencies. When we use these commands then it will automatically upgrade dependencies in package.json and yarn.lock file accordingly. yarn upgrade [package] yarn upgrade [package]@[version] yarn upgrade [package]@[tag]

 Example

In this example, we specify which version of the package we are going to upgrade from dependencies.

 Output

 7.Delete Dependencies

By using this command you will easily delete dependency. Package.json and yarn.lock files will be automatically upgraded accordingly. yarn remove [package]

 Example

In this example, we specify which package we are going to remove from dependencies.

 Output

Different data processing including interactive processing and stream processing could be done through yarn. It helps to process data which is stored in HDFS “Hadoop distributed file system”. This shows a plus point of yarn.

 Conclusion

This article conveys mainly the concept of Yarn. In this article, we learned what yarn is and also the common commands of Yarn along with examples to create a new project and adding/deleting dependencies. If you don’t know about Yarn then you must have a try of these commands.

What is the Difference Between =, == and ===?

JavaScript is a programming language that allows us to create and develop web applications and web pages as well as make our websites more dynamic/interactive. Data can be calculated, manipulated, and validated using JavaScript. Like any other language, JavaScript has operators. An operator produces a result by performing some action on a single or multiple operands (data value). Let’s look at an example of 2+2 where the numbers are left and right side operands and the + is the operator. This + operator adds the two numbers together. With examples, we’ll examine and answer the question that what is the difference between the =,==, and === operators in this article.

 What is = operator?

The = sign or equal to the operator is an assignment operator. The function of equal to is to set the value of the left-hand side to the right-hand side. For example a=10. In this example, the variable is set to the number 10. However, it should be noted that 10=10, ‘a’=’a’ will give a reference error as we are kind of comparing them instead of setting a value.

 Example of =operator

var num1=10;var num2=5; alert(num1+num2); Num1 and num2 variables are assigned values of 10 and 5and after this, we add both num1 and num2 and alert the result which can be seen in the above screenshot.

 What is == operator?

The == sign or Double equals function is called the equality operator and its function is to compare two values or expressions (compare strings, variables, numbers, etc). The result is true if the expressions are equivalent; otherwise, the result is false. However, it should be kept in mind that boolean, numbers, and string values are compared by value and not by reference hence If they have the same equivalent value then it is considered true. However, variables, functions, objects, and arrays are compared using reference, for example, two variables are only equal if they refer to the same object, function, or array.

 Example of == operator

var num1=10;var num2=5; alert(num1==num2); In this example, we took two variables and assigned 10 and 5 numbers to them. Then we alert by checking whether num1 and num2 are equal which results in a false statement as == operator checks by value. Now we change the code a little bit i-e assigned the value of 10 to num2 and then checked whether num1 and num2 are equal and it is as it returns a true value. var num1=10;var num2=10; alert(num1==num2);

 What is === operator?

The === sign or triple equals is called the strict equality operator and its function is to check whether the two operands are equal or not and return a true or false value. === operator returns false when the values are not of similar type and true when they are of similar type. To simplify we can say that the === operator performs typecasting, for example, let’s compare 1===”1” this will return false as the values are the same but the type is not the same. var num1=10;var str1="10"; alert(num1===str1); As discussed earlier, the === operator checks both the value and the type of two operands so we took a num1 and assigned an integer 10 to it. Then we took str1 and assigned a string of number 10. We then alert whether num1 and num2 are equal or not which returns as false as although the values are the same but the type is not the same, one being an integer and the other a string. Now we change the above code a little bit and initiated num2 with a value of 10 to it. We then alert whether num1 and num2 are equal which returns true as the values and the datatype are both same in num1 and num2: var num1=10;var num2=10; alert(num1===num2);

 Conclusion

JavaScript is a programming language used to build web applications and JavaScript offers operators which help in the calculation, manipulation, and validation of data. Operators perform some action on operands and return the result. In this article, we defined =,== and === operators and gave examples of these operators to shine the light on the differences among them.

Is JavaScript Object-Oriented?

Object-Oriented Programming (OOP), is a programming approach that is used by every developer at some point in their life to organize software design around objects or data rather than logic or functions where an object is an entity that has some properties and some type. The benefits of using the OOP technique include modularity, reusability, security, productivity, flexibility, and is easily scalable and upgradeable.

 Features of OOP

The three major features of OOP are as follows:

 i) Encapsulation

Encapsulation is a concept of OOP that bundles data and methods which operate on that data within one unit, for example, a class in java and an instance of a class is called an object. Encapsulation also refers to restricting data access to some classes or objects and hence all the users won’t be able to access variables or state values of some object.

 ii) Inheritance

In Inheritance one class (child) inherits all the methods and attributes of another (parent) class.

 iii) Polymorphism

Polymorphism means a property having many forms and is one of the core concepts in OOP. Polymorphism lets us create procedures about objects whose exact type is not known till runtime.

 JavaScript Object-Oriented?

JavaScript is a programming language based on prototypes and is mainly used to create web applications and web pages. Prototype programming language is a style of OOP in which objects that are already created can be cloned and reused so that the program or application can be constructed. Functions are used as constructors for classes in prototype-based programming languages. JavaScript is excellent in programming OOP applications and is heavily object-based however it is not a class-based OOP language but rather a Prototype-based programming language. However, we can use JavaScript as a class-based programming language. JavaScript allows you to make or create new objects for the use of your application. However, it should be noted that while OOP language encourages and focuses on relationships and taxonomy, prototype-based languages focus and encourage behavior first and then classification later. In 2015 JavaScript introduced a class keyword which was to make JavaScript OOP language but it was just synthetic sugar over the existing prototype technique. The outer body looks like OOP, however in the background the prototyping continues. Below is an example of OOP where we used class for defining student objects and has the property of name and grade and method studies() which returns name and grade of the student. class student { constructor(name, grade) { this.name = name; this.grade = grade; } studies() { return `${this.name} studies in ${grade}`; }} let myStudent1 = new student("Jhon", 6); console.log(myStudent1); If we expand the prototype seen in the above screenshot we will see that the proto references the student prototype which in fact references the Object prototype.

 JavaScript Encapsulation Example

Let us look at an example where inheritance is used and the person class or object is defined where a person has a name and a method is also defined where the name is returned. Another class student is defined which extends person hence inheriting all the properties and methods of parent class i-e person and in the child class i-e student class, we utilized the super keyword that invokes the constructor of the parent or person class. You will also be able to see that the person object and student object both have a method with the same name toString(). This is called overriding and OOP allows us to have a method in a child class with the same name and signature as that of the parent class. //Example of Inheritanceclass person{ constructor(name){ this.name = name; } //String returns from this method toString(){ return (`Name: ${this.name}`); }}class student extends person{ constructor(name,regid){ //super keyword used to call Parent constructor super(name); this.regid = regid; } toString(){ return (`${super.toString()}, Registration ID: ${this.regid}`); }} let myStudent1 = new student('Jhon',1032); alert(myStudent1.toString());

 Conclusion

OOP is a programming model that organizes our software design around objects rather than logic or functions. An object has some property and value. By using OOP we achieve security, productivity, reusability, and much more. JavaScript is a programming language that is based on prototypes, however in 2015 class keyword was introduced which makes JavaScript like an OOP programming language but as we saw in the above description that in the background prototyping continues. To put it simply, JavaScript is a prototyping-based Object Oriented Programming language.

How to disable scrolling on a webpage with JavaScript

JavaScript is a web language used for creating dynamic web pages and making them interactive for users. Through JavaScript we can perform various functions, change CSS of HTML elements, perform actions on each click and many more.JavaScript makes the page of our website more interactive and adds dynamic behaviors to it, we can create various menus, drop down menus, scroll bars etc. We can even enable and disable the behaviour of each of these components using JavaScript. In this article we’ll see how to disable scrolling on a webpage using JavaScript.

 Disable Scrolling on a Webpage

The scrolling on web pages can be easily disabled using JavaScript through various ways but in this article we’ll only see two ways to disable it which are listed below: Method 1: By overriding the window.onscroll function Method 2: By setting the height of the body to 100% and overflow to hidden Each of these methods are explained below along with examples for better demonstration and your understanding.

 By overriding the window.onscroll function

The event window.onscroll is fired when the window has been scrolled, thus overriding and setting the function to a fixed value will disable the scroll effect for your webpage. You can find the current position of scroll from top through window.pageYOffset and document.documentElement.scrollTop, both of which will return the current value of Y scroll. These two are used together using the OR logical operator “||” as one of them might return 0 on some browsers. Now, in order to find the value of X scroll we can use window.pageXOffset and the document.documentElement.scrollLeft which are used similarly as Y scroll, using or operator and they return the value for X scroll of the webpage. Now after this we’ll use window.scrollTo() along with the two above values to set the scroll position of your webpage to that value. You can enable the scrolling back by overriding the window.onscroll function to blank a blank function. Below is the code provided for disabling the scrolling of webpage using this method: HTML: <html><head><title>How to disable scrolling using JavaScript?</title><style> .scrollable-place { height: 3000px; }</style></head><body><h1 style="color:blue"> Welcome To Our Website</h1><p>Click the buttons below to enable or disable scrolling.</p><p class="scrollable-place"><button>Disable Scrolling</button><button>Enable Scrolling</button></p></body></html> JavaScript: functiondisable() {// To get the scroll position of current webpage TopScroll = window.pageYOffset || document.documentElement.scrollTop; LeftScroll = window.pageXOffset || document.documentElement.scrollLeft,// if scroll happens, set it to the previous value window.onscroll = function() { window.scrollTo(LeftScroll, TopScroll); };} functionenable() { window.onscroll = function() {};} Output:

 By setting the height of the body to 100% and overflow to hidden

In this method we use CSS to disable the scrolling on web pages. In CSS class we set the height to 100% and then we set the overflow property to hidden which disables the scroll bar of the webpage. The method document.body.classList.add(“classname”) is used to add the class name to the body element and hence disabling the scrolling. To enable the scrolling back the class is removed from the method using document.body.classList.remove(“classname”). HTML: <html><head><title>How to disable scrolling using JavaScript?</title><style> .scrollable-place { height: 3000px; } .stop-scrolling { height: 100%; overflow: hidden; }</style></head><body><h1 style="color: blue">Welcome To Our Website</h1><p>Click the buttons below to enable or disable scrolling.</p><p class="scrollable-place"><button>Disable Scrolling</button><button>Enable Scrolling</button></p></body></html> JavaScript: <script> functiondisable() { document.body.classList.add("stop-scrolling"); } functionenable() { document.body.classList.remove("stop-scrolling");</script> Output:

 Conclusion

JavaScript is used for various purposes such as creating input boxes, navigation bars, on click events actions etc. Through JavaScript we can also enable and disable the action of various components on our webpage. In this article we discussed how to disable scrolling on a webpage with JavaScript and discussed two different methods along with examples and code for better understanding of yours. Both these methods are easily used and can help users to disable the scroll bar easily.

How to enable or disable JavaScript on iPhone (Safari)

JavaScript is not just restricted to implementing web pages but is also used to build mobile applications, network applications, and web-based games. Nowadays, almost all the current websites are designed using JavaScript. JavaScript makes the web pages quite interactive with added features, not with traditional white pages of texts and images. iPhones have such platforms where JavaScript is quite handy, however, it has many misuses like hijacking the browsers. For instance, inducing the marquis search spams in safari browsers. For such incidents, being a privacy freak, I usually keep my JavaScript blocked. So, if you feel JavaScript is of no use, you can block it for all the websites. Unlike Chrome and edge for androids, safari doesn’t have the feature to run JavaScript on the customized list of sites, you can either turn it off for all the sites or allow it for. In this brief step-by-step guide, we will discuss how to enable and disable JavaScript on iPhone (Safari). You have to follow only a few steps and then you will be able to either enable or disable JavaScript on your iPhone (Safari).

 Disable JavaScript on iPhone(Safari)

Open Settings of iPhone

In this step, you have to open the settings application on your iPhone.

Open Safari

Once you open the settings then move down to find Safari from the menu items and once you find it tap on it to open its settings:

Open Safari’s Setting

After tapping on Safari then you have to tap on the advanced option.

Toggle JavaScript option

After tapping on the advanced option the following screen will be shown to you. Now if it is turned on then simply tap on the toggle button to turn JavaScript off (from green to black). If the button is toggled (black) then it shows that JavaScript has been successfully disabled on your iPhone (Safari). Now you just need to simply go back to the main menu screen and start browsing again.

 Enable JavaScript on iPhone(Safari)

If you want to enable JavaScript on an iPhone (Safari) then you simply need to follow all the above-mentioned steps and for the last step, you have to toggle the JavaScript button on (from black to green). Then in this way you enabled JavaScript on your iPhone (Safari) successfully.

 Conclusion

JavaScript is versatile and can be used everywhere. JavaScript makes web pages intuitive. In this article we discussed a step by step guide on how to disable JavaScript on iPhone (Safari), and also explained briefly how to follow all these steps to enable it again. If you disable JavaScript then you would not be able to achieve many of the website’s functionalities like animations and many more. Illustrations are also provided for each step to help you understand.

How to check if an array is empty

Knowing how to check for an empty array is an important coding skill which can often come in handy. It can be helpful in a situation where you have to show or hide something on a web page depending on whether the array is empty or not. Similarly, there are many other places where you will find this skill helpful. The purpose of this post is to explain the code, the concept behind the code and the most common use cases of checking for empty arrays code. So let’s get started

 How to check for an empty array

Checking for an empty array code is very simple, javaScript provides a simple length() method which helps to know the total number of elements of an array. If the length() method returns 0 then that means that an array is empty: varemptyArray = [];if (emptyArray.length === 0) { console.log('The array is empty.');}else{ console.log('The array has at least one or more elements.');} If we fill the array with elements then: varnotAnEmptyArray = [1, 2, 3, 4, 5];if (notAnEmptyArray.length === 0) { console.log('The array is empty.');}else{ console.log('The array has at least one or more elements.');} The thing about the .length method is that it can work with data types other than arrays: varnotAnArray = 'This is not an array.';if (notAnArray.length === 0) { console.log('The array is empty.');}else{ console.log('The array has at least one or more elements.');} As you can see in the example above, the code was interpreted by the browser without any errors even though there was no array present in the code. So if we are unsure about the data type of our variable, we might first want to check whether it’s an array or some other variable. For this purpose we will not use typeof operator as arrays are instances of objects and their data types are objects. Rather we will use the Array.isArray() method: varnotAnArray = 'This is not an array.';if (Array.isArray(notAnArray)) {if (notAnArray.length === 0) { console.log('The array is empty.'); }else { console.log('The array has at least one or more elements.'); }}else{ console.log('The given variable type is not array.')} If we change the variable to an empty array: varnotAnArray = [];if (Array.isArray(notAnArray)) {if (notAnArray.length === 0) { console.log('The array is empty.'); }else { console.log('The array has at least one or more elements.'); }}else{ console.log('The given variable type is not array.')}

 Conclusion

Checking whether an array is empty or not is a kind of a coding problem that can often be asked in quizzes and exams. In this post we learned to use the length() method to know if an array is empty or not. The process of checking whether an array is empty generally consists of two steps. The first step is to know if the variable’s type is array type or not. The second step is to know the total number of array elements using the length() method; if the length is equal to 0 then the array is empty; otherwise if it is greater than 0 then the array has some elements in it.

What is Vanilla JavaScript?

JavaScript is a programming language used both for the client-side as well as the server-side to make our websites interactive by giving us the edge of implementing complex features on our website. If you visit Amazon there is the search bar at the top of the website which is developed using JavaScript. JavaScript (Js) is one of the most recommended programming languages out there and a necessity for a beginner web developer. However, as you go in depth of JavaScript you will come across frameworks and libraries which you will learn to make your lives easy. But before going into the frameworks and libraries, people recommend that you should have a strong base with Vanilla JS. Wait! What really is Vanilla JS? Is it a framework or a library? Don’t worry, we’ve got you covered; in this post, we’ll go over all there is to know about Vanilla Javascript, including its benefits and drawbacks.

 What is Vanilla Js?

Vanilla Js is plain JavaScript with no difference whatsoever. Vanilla Js is the purest form of Javascript with no addition of any library and using the inbuilt functions/methods and objects. To make our webpage work, you do not need to download any other tools or libraries and Vanilla means something that is ordinary or something standard with no extra or special features. Plain JavaScript is lightweight where you can create amazing websites using basic and straightforward scripts. The Vanilla JavaScript developers are continuously making an effort to make vanilla JavaScript more useful for web developers. The importance of Vanilla Javascript can be taken from the fact that many popular and known websites are developed using vanilla JavaScript. Some of them are: Youtube Wikipedia Facebook Yahoo Amazon Twitter Paypal Netflix Stack overflow And many more.

 Why learn Vanilla JS?

Now that we know what Vanilla Js is, let us explore the idea of why we should even learn Vanilla Js when there are so many libraries out there that can make our lives easy. Let’s look at a few reasons why you should use Vanilla JS:

 User Friendly

Vanilla JS is very easy to handle and a revelation for beginners as they don’t have to dig in and install libraries and learn about npm, or the compilation steps as well as no build. One just needs a text editor to start coding thus making Vanilla JS user-friendly as well as effortless.

 Builds a base

If you don’t feel familiar with Vanilla JS and move on to other frameworks, such as node js or react js, believe me when I say that you will struggle to master such frameworks and will eventually need to return to Vanilla JS to grasp some fundamentals. Why move back and forth when you can go in one direction by first establishing a strong foundation and then moving forward?

 Better web performance

For the front-end web, it is the most important part, and rightly so as it gives a much better web performance than most of the frameworks and libraries that are available right now. Unlike HTML or CSS the Vanilla JS needs to be parsed and compiled and a 30kb Vanilla JS file has a more significant impact than the same size of the file of HTML and CSS on web performance.

 Speed

Vanilla Js does not need any external resources for which purpose the execution of Vanilla JS code occurs on the client-side hence making its speed excellent. It should also be kept in mind that the speed of Vanilla JS is not affected by the calls to a back-end server.

 Disadvantages

Now that we have discussed the advantages of Vanilla Javascript let us flip the coin and discuss the other side, that is the disadvantages of using Vanilla JS: Lacks Debugging utilities. No support for the network-based applications hence cannot be used to develop network-based applications. No multiprocessors as well as no multithreading. As the code is available on the client-side hence people can modify that code and use it for malicious activity.

 Conclusion

Vanilla Javascript is just another term that is used for plain JavaScript. The libraries and frameworks are getting popular day by day and they exclude a lot of repetitive code but they are not a necessity. Vanilla Js is used by a number of well-known web apps, including Facebook, Twitter, and many others. In this article, we shed light on what Vanilla JavaScript is and why we should use Vanilla JavaScript by discussing its advantages. We hope you gained the purpose of coming into this article and we hope you have learned a bunch of stuff.

What is Node JS and What is it Used for?

Every web developer must have heard about Node js and it is getting more famous day by day because of Node js fast and scalable web applications development and the constantly growing Node js community. Before we go to what Node js is let us have a look at what Web apps use Node js. Popular Web applications in Node.js Netflix Paypal LinkedIn Uber eBay

 What is Node JS?

Node.js is an open-source back-end run time environment of JavaScript that runs on a v8 engine(Google Chrome JavaScript Engine) and can execute JavaScript code outside the browser. Node js was developed in 2009 by Ryan Dahl and Node js function is to make building fast and scalable network applications easy. It is lightweight and efficient and a perfect candidate for data-intensive real-time applications that can run on different distributed devices because of the usage of the event-driven and non-blocking I/O model. Node js is not a framework of JavaScript but a runtime environment for server-side and networking applications and JavaScript language is used for the creation of Node js applications.

 Node.js Features

Now that we know what Node js is let us discuss the main features of Node.js: As mentioned earlier Node.js is built on a v8 engine which makes the Node.js library very fast in code execution. The Node js API libraries are entirely asynchronous and non-blocking, which basically means that the server never waits for an API to return or provide data and instead moves on to the next API once the previous one has been called. Node.js is highly scalable but single-threaded. Node.js applications output data in chunks hence no buffering.

 What is Node.js used for?

Node.js is very useful when it comes to developing applications and running JavaScript on both the client and server-side and some of the usages of Node.js are:

 Streaming Applications

You must have heard of Netflix which is one of the largest media services providers by offering over 150 million users of streaming content. Netflix moved half of Netflix API to Node.js in 2018 because of a common language on both the Server-side as well as client-side and the benefits of Node js i-e asynchronous non-blocking I/O capabilities.

 Chat applications

Node.js is famous for its real-time development applications and is widely used by developers for developing real-time applications because of its handling of heavy input-output operations. When designing chat applications, developers frequently choose the Socket.IO library because it allows for bi-directional, real-time, and event-driven communication between the browser and the server and When Socket.IO and Node.js are combined, it becomes incredibly simple to create chat applications with as few as 30 lines of code for a group chat application.

 Browser games

Node.js is also used to build and develop games with a combination of HTML5 and Socket.io library which run in the browser without any third-party plugins like adobe flash player etc.

 Command-Line Applications

Node.js with the help of libraries like a commander and yards makes creating command-line applications simple, fast, and extremely cost-effective as JavaScript is used both on the front-end and back-end.

 Where Node.js is avoided

Now that we have discussed what Node js is used for, let us discuss where Node js should be avoided. Server-side Web application with Relational Database as a backend Heavy processing at Server-Side Intensive CPU computations

 Conclusion

Usage of Node.js is growing day by day and some of the top companies are shifting their APIs to Node.js. One such example is Netflix. Judging by the popularity of Node.js in the huge community of developers and newbies learning Node.js, it is safe to say that Node js will grow more in the future and is worth learning. The simple definition of Node js is that it equals JavaScript library and runtime environment. In this article, we discussed what Node.js is and what Node Js is used for. Apart from that we also discussed some of the features of Node.js and pointed out the major Web applications that use Node.js.

What is the Window Print() Method?

The window print() method is used to print the visible contents of the current window, for example, a web page text or image by displaying the Print Dialog Box which allows the user to choose from a variety of printing options, and the Print Dialog Box is only opened when the print() code is executed.

 Syntax:

window.print(); This will open a Print Dialog Box which will print the visible content of the current window as discussed earlier. It should be noted that the window.print() method does not take or contain any parameters and also doesn’t return anything.

 Browsers Support

The window.print() method is supported by many browsers and some of them are as follows:
BrowserChromeInternet ExplorerFirefoxSafariOpera
SupportYesYesYesYesYes

 Example

HTML: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <h2>Window Print Example!</h2> <button class="btn">Click Me</button> <script src="code.js"></script></body></html> In the above HTML code, we defined h2 tags and then created a button that says Click me. After this, we put the script tag which is referencing code.js which will make JavaScript connect to HTML. JavaScript: const btn= document.querySelector(".btn"); btn.addEventListener('click', function(){ window.print();}); In the above code, we are referencing the button in the HTML by using the class anime associated with it. After this, we added an event listener of click which will continuously listen for a click event and whenever someone clicks on the Click Me button, the function within the event listener will run. When we first execute the above code of HTML and JavaScript we will see the following on our browser: When we click on the Click Me button, the Print Dialog box will open: We can see the content of our webpage on the left-hand side of the Print dialog box and when we click on the print button it will print or save the current viewscreen in a file.

 Conclusion

We learned everything about the window.print() method and answered the question of what the window.print() method is along with an example in this post. To recap, the window.print() method prints the current windows visible content which can be anything like image, text, or any advertisement. We also saw that whenever the window.print() method is executed the print dialog box opens where a user can choose their preferred options to print the document.

What is a JavaScript Framework?

Any web developer is familiar with HTML, CSS, and JavaScript. HTML is a hypertext markup language that gives structure to our websites, CSS gives style and JavaScript makes our websites interactive and responsive. The next step is to explore JavaScript Frameworks. JavaScript Frameworks are a group of JavaScript frameworks that give programmers pre-written JavaScript code to utilize for common programming tasks and aids in the development of web applications and web pages. Frameworks are not a necessity and strong web applications can also be built without using these frameworks; however, these frameworks provide developers with a template that handles common programming patterns. Let me put it another way; if you are a web developer and you are building websites and web applications, wouldn’t it be better to use pre-written codes instead of writing the same program from scratch. The framework does the same thing by providing you with an existing feature set that you can use and build websites or web applications. By following JavaScript frameworks, rules and guidelines anyone can make a complex web application that is faster and more efficient than developing a web app from scratch. The JavaScript framework rules and guidelines help us structure and organize our code. We can think of it as a pottery wheel that rotates and we have to work with it to make different shapes and sizes of pots, plates, bowls, etc but the pottery wheel cannot make a house with it as we need a different framework to work for that. Let’s move on to another topic: framework and a library difference. The difference between these two is very blurry however let me simplify it for you a little bit that a framework organizes your web application or website having a full toolset whereas a JavaScript library is pre-written JavaScript code that provides some features and they are less about shaping our application.

 MVC (Model View Controller)

JavaScript frameworks are built around the MVC design architecture so that we will have structure as well as adaptability in software development. The model view controller is just a software design architecture that divides programming logic into three different interconnected parts. The first part is the Model which handles application data and provides dynamic data structure hence becoming the central component of the Model view controller. The view part handles all the code that represents the user interface and the controller part acts as the interpreter by accepting some input and converting that input into commands for the view or model part.

 JavaScript Frameworks

JavaScript has by far the most frameworks than any other programming language and since it is used both for the client-side as well as the server-side there are different popular frameworks available for each of them. We’ll go over both the front-end and back-end frameworks for JavaScript.

 Front End Frameworks

A front-end framework is a development platform for your front end and usually includes a method for creating files, associating data with DOM elements, styling components, and making AJAX queries, and some of them are discussed below:

 Angular

Angular is by far one of the most popular front-end frameworks of javascript which was developed by Google and is supported by both Google as well as Microsoft and is a free and open-source enterprise-level JS framework that aids developers in the creation of large and sophisticated corporate applications.

 React

React is created by Facebook and is basically a JavaScript library but it is discussed in terms of Framework as React is very efficient and flexible. React best features include predictable code and easily debugged code which is used to create interactive user interfaces. The best thing about React is that it divides its code into components hence blocks of code written once can be reused for different parts of that application. Suppose you designed a button in a webpage, and then you need to use that same button somewhere else in the application, you don’t have to write the code from scratch but just import the button component where you want to reuse the button.

 Vue

Vue.js is a JavaScript framework that is used to develop user interfaces for creating complex and single web pages or applications. Vue framework helps developers by making integration with other existing projects as well as other libraries very easy.

 Back-end Frameworks

Backend frameworks are collections of server-side computer languages that aid in the development of a website’s backend structure and offer pre-built components for building dynamic web applications. Using frameworks gives developers an advantage by removing the requirement to construct and configure everything from scratch. Some of the back-end frameworks are discussed below:

 Express.js

Express js is one of the most popular and widely used Node js frameworks for server-side applications by giving developers flexibility and by being lightweight as well as the minimalist framework. Express js features include high-performance speed as well as it gives developers a wide range of HTTP utilities.

 Next.js

Next. js is a minimalistic framework that gives developers an edge on creating static web pages/applications as well as server-side rendering using the popular React Js framework. As demonstrated on the Facebook scale, Next js is a quick, dependable live-editing experience.

 Conclusion

JavaScript Frameworks are collections of JavaScript libraries having pre-written Js code used for routine programming features and makes our web pages interactive. The JavaScript frameworks make JavaScript very easy to use as well as are adaptable in web application designing. There are multiple JS frameworks each having its own features and solutions to different problems. In this article, we discussed what JavaScript Framework is and went through a few JavaScript frameworks including front-end and back-end frameworks. Frameworks make our lives easy and when choosing a Js framework always learn about your project requirements first and then choose the framework based on those requirements.

What is Angular JS?

HTML is a hypertext markup language that gives structure to our web applications and web pages and is great for static document declaration but HTML hesitates in declaring dynamic views in web applications. The solution is AngularJS which extends our HTML vocabulary. AngularJS is one of the most popular, open-source, structural front-end frameworks that is used for dynamic single web applications which change static HTML into dynamic HTML and was developed in 2009 and is currently maintained by Google. AngularJS extends HTML ability as it lets us add built-in attributes and components as well as provides the ability to create custom attributes using simple JS. The official website of AngularJS is given below from which you can download AngularJS: https://angularjs.org/ AngularJS uses the Model view controller software architecture as most JavaScript frameworks.

 Model View Controller

Model View Controller (MVC) is a software architecture design that divides our application into three logical components: Model is the part of the architecture where data is represented. For example, if you are building a school management system then the data of students (registration number, name, age, etc) are present in this part. Views are simply the presentation layer that is shown to the users. Controller represents the business logic, i-e user events trigger functions initialized in the controller.

 AngularJS Features

Angular has some unique features that make it so popular. Some of them are: AngularJS offers data model binding which means that one doesn’t need to write some special code for binding data to HTML controls and is done with just a few snippets on AngularJS. As previously mentioned, AngularJS is based on the well-known MVC design pattern, which is employed in the majority of current apps. AngularJS makes us write less code as compared with JavaScript Dom manipulation, Angular has less code for Dom manipulation. Another feature that AngularJS offers is the testing framework Karma designed by google which performs unit tests for AngularJS applications.

 Angular JS Advantages

Open-source framework hence less number of errors. Single Page Application creation is achieved in a very maintainable and clean environment. Rich and Responsive experience with data binding capability is provided in HTML. Routing is moving from one page to another and Angular makes it very easy and efficient as there is only a single page; however you can change views based on your preference/requirement. Provides reusable components Separation of concerns and dependency injection is used. No need for learning a new language as it is pure JS and HTML. AngularJS applications run on all major browsers as well as android and ios mobiles.

 Angular JS Disadvantages

Now that we have discussed the advantages of AngularJS let us flip the coin to the other side and discuss some of the disadvantages of AngularJS. Server-side authentication and authorization are a necessity to keep our application secure, hence AngularJS applications are not safe. AngularJS is not degradable which means if the user disables the JavaScript then nothing would be visible except the basic page

 AngularJS Directives

Angular Js provides us with unique and powerful Directives which let us invent new HTML syntax pacific for our application. AngularJS is divided into three parts: The directive responsible for linking HTML and AngularJS applications is the ng-app. The directive responsible for binding the values of Angular js to Html input controls is ng-model. The directive responsible for binding the AngularJS application to HTML tags is ng-bind.

 AngularJS Directives Example

Suppose there is an input box and we want to display the typed string in the label then we will use the ng-app,bg-model as well as ng-bind in the below example to achieve our purpose: <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script></head><body ng-app> Enter Name: <input type="text" ng-model="name" /> <br /> Hi! <label ng-bind="name"></label></body></html>

 Conclusion

HTML is great for static documents however for declaring dynamic views HTML falters. AngularJS extends HTML vocabulary and is one of the most popular web frameworks which is used to design single web pages. This article was an introduction to What AngularJS is and we covered almost all of the theoretical part of what AngularJ is.

What is Express JS?

Express.js is a node.js web framework used for the back-end web applications and web pages. Express is under MIT license so it is open for everyone to use and freely available. Express Js is mainly used to build web applications and APIs and it makes the process very easy and quick because it only requires javaScript. Web applications are simply web apps that one can run on the browser. Express js is very popular among the back end as well as the full stack web developers because of its flexibility and minimal features as well as providing a robust set of features for both web and mobile applications. Node.js is a run-time open-source environment that allows users to run JavaScript both on the client-side as well as the server-side. Node. js is built on the v8 chrome engine and can run on different platforms like Windows, Mac Os, Linux, Unix, etc. Express facilitates quick development of Node.js based web applications and some of the core features of Express js is as follows: Allows middlewares set up to respond to HTTP requests Faster server-side development Offers highly advanced routing system Allows building of dynamic web pages by providing template engines. Debugging mechanism is provided hence making debugging easy

 Advantages of Express JS

Now that we know what Express js is and what are the features of Express js, let us take another step and pinpoint some of the advantages of Express js: Easy to learn as everything is done and hence no need of learning another language. For front-end developers, developing the back-end becomes easy using express js. One can become a full-stack developer by using just one language. Express Js framework usage and customization is very simple Express provides a middleware module that is flexible and used for performing some extra tasks on response and requests. Complexities of Node js is taken away as well as helpful functions are added to the Node.js HTTP server Ultra-fast I/O Handling requests is easy as small modular and maintainable functions are provided.

 Install Express JS

We can install Express js by opening our editor terminal or operating system CMD and executing the below-mentioned command: $ npm install express --save The above command will install Express js globally using npm hence this can be now used to build web applications using the node terminal. Also, installation is now done in the node_modules directory and a new directory is created with the name of express inside the node_modules directory.

 Express JS Example

Let us now implement an example in express js where we will start a server and listen on port 8000 for connection and the output that it will give is the Welcome Beginners! Whenever the homepage will be called. However, it should be kept in mind that if you access another page or URL, it will give an error of 404 Not Found. //import expressvar express = require('express');var app = express(); app.get('/', function (req, res) { res.send('Welcome Beginners!'); });var server = app.listen(8000, function () { var port = server.address().port; console.log("Listening at port", port); }); Open your editor terminal and execute the following command in your editor terminal: $ node example.js Next open the browser and search for the following link: http://localhost:8000/ When you search the above link you will see the Hello Beginners! Output: Congratulations! You have successfully created your first express js application.

 Conclusion

Express Js is an open-source, free Node.js web framework released in 2010 and is robust, fast, and asynchronous in nature. We can also say that Express js is just a layer built on top of Node js that helps in managing routes and servers. Express is used to develop both web and mobile applications while Node.js is a run-time environment built on the google v8 engine. In this article, we covered the introductory part of Express Js and discussed what is Express js, and then went through Express Js features and advantages. On top of that, we also installed Express Js in our VS code editor and explained an example. We hope by following this article, you must have gained the required knowledge of what is express js.

Conditional statements

Many times the developer wants different outcomes, depending on the action that is taking place. For this purpose, JavaScript provides us with conditional statements. Following are the conditional statements: If (contains specific code that needs to be executed if the conditions mentioned are true) else (contains specific code that needs to be executed if the conditions mentioned are false) else if (contains a new condition if the first condition mentioned is false) switch (contains various blocks of codes that needs to be executed) Let’s understand each of these better with example:

 The if statement

The if statement contains a specific code that needs to be executed if the condition that is mentioned is true. Keep in mind that writing If or IF instead of if will generate an error. Syntax: if (condition) { // execute the if block if the condition is true} Here the situation for which the code will enter the if block is defined in the place of condition. Example: <!DOCTYPE html><html><body><p>Click the button to display "Good Morning", only if the time is less than 12 PM.</p><button onclick="Display()">Display</button><p id="div"></p><script> function Display() { var time = new Date().getHours(); if (time <12) { document.getElementById("div").innerHTML = "Good Morning"; }}</script></body></html> In this example, it’ll only be executed if the time is less than 12 PM. Otherwise, there will be no output. Output: You can also execute multiple if conditions in which each if condition will be checked, but, it’s better to use if-else condition instead of using multiple if conditions at once.

 The if else statement

Using a single if statement mostly isn’t beneficial as the code executes without any output if the condition in the if block is not true. Well, for this purpose we use if..else condition which is used along with if to ensure that if the condition in if blocks is false then execute the else block. Syntax: if (condition) { // execute the if block if the condition is true}else { // execute the else block if the condition of if block is false} Here along with if we have else as well, which shows if the condition isn’t fulfilled then execute the else part of the code. Example: <!DOCTYPE html><html><body><p>Click the button to check if the number is less than 5 or greater than 5.</p><button onclick="Display()">Check</button><p id="div"></p><script> function Display() { var x = 7; if (x <5) { document.getElementById("div").innerHTML = "Number Less than 5"; } else { document.getElementById("div").innerHTML = "Number Greater than 5"; }}</script></body></html> Here, the else condition is executed as the condition inside the if block was not true Output:

 The else if statement

Sometimes, the user wants to check various conditions if the first condition is false and for this purpose else if condition comes to use. The major advantage is that we can check more than one condition using else if according to the flow of our program. Syntax: if (condition1) { // execute the if block if the condition is true}else if(condition2){ // execute the elseif block if the condition of if block is false true}else { // execute the else block if the condition all above are false} Here along with if else, we’ve a third block of code else if which contains another condition that needs to be checked, and a code can have multiple else if blocks. Example: <!DOCTYPE html><html><body><p>Click the button to check if the number is less than, equal to or greater than 5.</p><button onclick="Display()">Check</button><p id="div"></p><script> function Display() { var x = 5; if (x <5) { document.getElementById("div").innerHTML = "Number Less than 5"; } else if(x == 5){ document.getElementById("div").innerHTML = "Number is equal to 5"; } else { document.getElementById("div").innerHTML = "Number Greater than 5"; }}</script></body></html> Here, the program checked the condition and executed the else if part as the number mentioned was equal to 5. Output: Furthermore, we can also use comparison as well as logical operators in the conditional statements to check more than one condition as a single condition, more precisely. Comparison Operators (, ===, !==, >=, <=) Logical Operators (&& checks two statements both of which need to be true for the code to be executed. Whereas, || checks two statements of which only one can be true for the code to be executed) Example: <!DOCTYPE html> <html> <body> <p>Click the button to check which range the number falls into.</p> <button onclick="Display()">Check</button> <p id="div"></p> <script> function Display() { var x = 13; if (x >0 && x<=5) { document.getElementById("div").innerHTML = "Number between range of 0-5"; } else if(x>5 && x<= 10){ document.getElementById("div").innerHTML = "Number between range of 5-10"; } else if(x>10 && x<= 15){ document.getElementById("div").innerHTML = "Number between range of 10-15"; } else { document.getElementById("div").innerHTML = "Number Greater than 15 "; }} </script> </body> </html> Output: In the above example, the user checked various conditions using the logical operator. Program checked both the conditions mentioned and executed the code if both were true.

 The switch statement

In order to execute various numbers of statements that can not be checked using else if as it looks unprofessional, then these statements are better to be executed using a single switch statement. In switch, we just simply assign cases to each code which can be a number or a string. Syntax: switch(statement) { case a: // code break; case b: // code break; default: // code } The statement is checked once and each case is checked against it. If no case matches, then the default code block is executed. Example: <!DOCTYPE html><html><body><h2>JavaScript switch Conditions</h2><p id="div"></p><script> let day; switch (new Date().getDay()) { case 0: day = "Sunday."; break; case 4: day = "Thursday"; break; case 5: day = "Friday. Weekend almost here"; break; case 6: day = "Finally it's Saturday"; } document.getElementById("div").innerHTML = "Today is " + day;</script></body></html> Output: Here, the statement was checked against each case and the output was generated when it matched the case.

 Conclusion:

In this article we learned how condition plays an important role in programming. Javascript provides us with various conditional statements that help us maintain the flow of our program according to decisions that need to be made. Through this you can organise your program more logically and control it for better performance. In this way the program becomes easily understandable as well for others.

Common Mistakes to avoid while coding

No matter what level of developer you’re in, there are chances that you’ll make a mistake. These mistakes can vary from syntax to complex functions mistakes that’ll end up causing a series of errors in your application. It’s a good thing to have a senior developer to look over your code and find the mistakes, but, it’s better for you to learn from your own mistakes and blunders and improve them with time. Although JavaScript is an easy to learn language, still, many developers, no matter how good of developers they’re, make some common mistakes. These mistakes cause your code to look inefficient, disorganized and full of errors. Here, in this article we’ll cover common mistakes to avoid while coding in order to make your code error free and efficient.

 Common Mistakes In Your Code

Following is the list that we’ve gathered regarding the common mistakes made by all kinds of developers. In this way you can understand the concepts better and avoid these mistakes in future.

 Incorrect Way Of Placing Your Script:

The most common mistake developers make is putting their script in an HTML file incorrectly. Most of the time the script is accessing HTML elements. By placing the tag in the head of an HTML file will cause an error. Here’s an example: <!DOCTYPE html><html> <head> <script>document.getElementById("div").innerHTML ="Hello, Welcome To Our Website"; </script> </head><body> <div id="div"></div> </body></html> This will not generate any output, whereas, placing the script tag at the end of your page will resolve this problem. But still, if you want to use a script tag in the head of an HTML file simply add the attribute “defer” in the script tag. Here’s an example of using defer. <!DOCTYPE html> <html> <head> <script src = "bundle.js" defer></script> </head> <body> <div id="div"></div> </body> </html>

 Incorrect Use Of (=), (==), (===) Operators

In JavaScript, another common mistake is the incorrect use of “=”, “==” and “===”. The “=” operator is an assignment operator which is used to assign values to different variables. Whereas, “==” and “===” operators are used for comparison. “==” is used for “loose” comparison of two variables ignoring their data types. While “===” is a strict comparison operator that checks the data type of two variables. Below is an example to understand the difference of each operator better and improve your concept to avoid such mistakes: let x = 55; let y = 55; let z = "55"; console.log(Boolean(x==y)); console.log(Boolean(x===y)); console.log(Boolean(y==z)); console.log(Boolean(y===z)); Here, first we assigned the variables some values using “=” assignment operators. Then using comparison operators we compared their values. Output: Here, when we compared the string with a number, “==” gave us true because it didn’t check the data types of both variables. Whereas, “===” gave us false, as it stricity checks the data types of variables as well.

 Addition VS Concatenation

For both adding numbers or strings the operator “+” is used. Because of this we get different outputs. For example, if we add a number with a numeric string it’ll generate a different output as compared to adding two numbers. let x = 5; let y = "5"; let z = 20; console.log(x+y); console.log(x+z); Output: As we can not define the type of data while declaring variables, and if these types are not properly handled, it causes some unpredictable results shown through the above example.

 Undefined VS Null

Both of these may look similar but they’re totally different from each other. Undefined is when you’ve not assigned a value to any variable. Whereas, Null is an assignment value that can be assigned to variables. Even if you compare these two through a strict comparison operator, it’ll give a false value. Here’s an example: let x; let z = null; console.log(x); console.log(z); console.log(typeof x); console.log(typeof z); console.log(Boolean(z===x)); Output: Here, the type of undefined is undefined whereas that of null is an object. Hence when compared, it generated false as an output.

 Semicolon Misplacement

The most common mistake developers make is placing the semicolon at the end of a function. For example: let x = 1;if (x == 19);{ console.log("Hello");} In this, the placement of “;” semicolon at the end of the second line will execute the given block of code no matter what the condition was. Output: To avoid this type of mistakes, rewrite your code as: In this way it checked the condition and hence no output was generated.

 Breaking a String

To break a string from the middle or start your sentence from the next line, you can not intend it. Rather, you’ve to use backlash “\” for this purpose. let x = "Hey \ there"; console.log(x); Output:

 Conclusion

In this article we discussed various common mistakes made during coding. Anyone can make these mistakes, so it’s better to understand the JavaScript working with more depth. Learning from these mistakes and avoiding them in future will help you create a more organized and efficient code. Not fully understanding the working of JavaScript can lead to stupid mistakes that causes erros in your program. Next time when you’re coding keep the above points in your mind and create an error-free code.

Inherit another Class’s methods using extend keyword

With the additional features and the simpler class syntax, ES6 made JavaScript a lot simpler. Prior to this, JavaScript inheritance was made possible with the object.prototype property which was very much different and complex in comparison to Java and C++ and other such programming languages. In this post, we’ll look into inheritance using the “extends” keyword. Examples do help in grasping the concept strongly so we are going to give examples as well. Let’s get started.

 What is Inheritance?

Like any other programming language, inheritance is a very important concept object-oriented programming. The simplest definition of inheritance is when methods and attributes from a parent class or a base class get copied or inherited into derived or child classes. It is very useful as due to this we are able to achieve code reusability. Code reusability means reusing attributes/properties and methods of a class in another newly created class.

 Extends Keyword

Now that we have looked at what inheritance is. Let us discuss how to achieve this. Like mentioned earlier, we used to achieve inheritance via object.prototype which is called prototypal inheritance. However, a more easy approach was followed which was using the extend keyword. The function of extending keywords is used to create a derived class/child class from a parent class/base class. The child class can inherit any class and that class becomes the parent class. When we inherit, in the child class all the methods and attributes will be inherited from the parent class. Syntax: class childClass extends parentClass; It should be kept in mind that it only works in ECMAScript 2015 (ES6) version.

 Which Browser supports the “extend” keyword?

Now let’s see which browsers support the “extend” keyword.
ChromeEdgeFirefoxSafariOpera
49.013.045.09.036.0
Now that we have covered the theory of inheritance and the “extend” keyword let us implement it. Example: classAnimalName { constructor(name) {this.animalName = name; } present() {return'Name: ' + this.animalName; }} classAnimalextendsAnimalName { constructor(name, quantity) {super(name);this.quantity = quantity; } whatAnimal() { returnthis.present() + " Quantity: "+ this.quantity; }}Const animal = new Animal("chicken", 5); alert(animal.whatAnimal()); In this example, we have a parent class “AnimalName” where we set the name of the animal. It has a method with the name “present()”. We have another class “Animal” which extends “AnimalName”. It means the “Animal” class is a child class and will inherit all of the “AnimalName” methods. We have a method in the “Animal” class by the name of “whatAnimal()”. In this, we are inheriting the “AnimalName” class method “present” and then created an instance of the “Animal” class. Now when we alert the whatAnimal() function it will work properly. It’s worth noting that we used the super() keyword to refer to the parent class in the above example. When we call the super() method we are in fact calling the parent class constructor and we can access all of the parent’s methods and properties thanks to the super keyword.

 Usage of getter and setter in Inheritance

When we use classes and inheritance, it is almost impossible not to use getters and setters. It is very helpful to retrieve or update properties before returning or setting those properties. The “get” keyword is used to retrieve or get a property. The “set” keyword is used to update or set some property. For Example: classAnimalName { constructor(name) {this._animalName = name; } get getAnimalName(){ returnthis._animalName; } set setAnimalName(nam){this._animalName = nam; } present() {return'Name: ' + this._animalName; }} classAnimalextendsAnimalName { constructor(name, quantity) {super(name);this.quantity = quantity; } whatAnimal() { returnthis.getAnimalName; }}const animal = new Animal("chicken", 5); alert(animal.whatAnimal()); In this example, we used the underscore character because we wanted to separate getter/setter from the actual attribute/property for better understanding. This example is identical to the previous one, with the exception that the “AnimalName” class now has a getter and setter. We retrieve the animal name from the parent class through the get method which is “getAnimalName”. We can also set a property in the same way by adding just one more line using the above code. classAnimalName { constructor(name) {this._animalName = name; } get getAnimalName(){ returnthis._animalName; } set setAnimalName(nam){this._animalName = nam; } present() {return'Name: ' + this._animalName; }} classAnimalextendsAnimalName { constructor(name, quantity) {super(name);this.quantity = quantity; } whatAnimal() { returnthis.getAnimalName; }}const animal = new Animal("chicken", 5); animal.setAnimalName="Cow"; alert(animal.whatAnimal()); The output will now be updated to “cow”.

 Conclusion

Inheritance is one of the core concepts of Object-oriented programming and the definition of inheritance can be defined as when the methods and attributes from a parent or base class get copied/inherited into a child or derived class and can be achieved using the keyword extends. If you read this article thoroughly, I am pretty sure that you guys have an idea of how to use the extends keyword in accessing the parent class methods and attributes. We explained inheritance, extend keyword, set keyword, get keyword, and which browser supports the extend keyword. Prototypal inheritance, as stated at the outset of this article is outdated and complex. Extend is more simple and similar to other languages like Java, C++, etc.

What are Scope and Closure?

When you are first starting JavaScript you might have come across scope and closures. These are very important concepts to learn for a beginner. Even in interviews, the interviewer asks about closures.Today we are going to discuss what scope is and what are the basic concepts of scope. After having discussed the scope, we’ll go towards closure and will discuss that. By the end of this article, you’ll have knowledge of scopes and closure. Before starting I would suggest that you don’t jump directly to closure without understanding the scope. The reason for this is that for the closure concept, understanding the scope concept is very important.

 Scope

The variables you have access to is the scope of that variable and is divided into two parts:

 Global Scope

If a variable is accessible throughout the program it has global scope. In other words, we can say that if a variable is outside of all functions and curly braces, it is a global variable and has a global scope. An example of global scope is: const globalName="John Cena"; Now that we have declared the variable with the name globalName we can get its value anywhere in the code including functions/methods. For Example: //global variableconst globalName="John Cena";//function with the name of greet function greet(){ console.log("Hello", globalName);}//calling the function greet greet();//accessing global variable again outside function console.log("Hello again", globalName); In this example, first, we initiated a variable with the name of globalName. After that, we constructed a function where we greeted the global name. Then we called the function with this statement greet(). After this, we console.log the globalName variable to see whether it’s accessible outside the function or not. The output shown in the console is: However, it should be kept in mind that most programmers do not recommend declaring a variable globally because there is a risk of duplicate variable names while doing so. Duplicate variable names occur when two variables have the same name. In most cases, this will cause an error that will be hard to debug.

 Local Scope

As the name suggests, a local variable has a local scope. That means it is only accessible within a function/method or block of code. Outside that area, it’s not accessible and JavaScript will generate an error. Local scope is divided into two sorts.

Function Scope

If a variable is declared within a function, it will only be accessible within that function and will not be accessible outside of it. For Example: //function with the name of greet function greet(){//local variableconst localName="Randy Orton"; console.log("Hello", localName);}//calling the function greet greet();//accessing local variable again outside function//this will generate an error console.log("Hello again", localName); In this example, we initiated a variable localName and then console.log it. This will show us the output of “Randy Orton” in the console log. However, when we console.log the local variable in the last line, it will generate an error. Output:

 Block Scope

Block scope tells us that if we declare a variable within curly brackets, those curly brackets will be its scope. That is called a block scope. One cannot access the block scope variable outside the curly braces. For Example: {const name="Rey Mysterio"; console.log("Hello", name);} In this Example we declared a variable having block scope as it is inside the curly brace. We console log it afterward. The output of “Hello Rey Mysterio” is seen in the console log. However, when we console log it outside the braces an error will be generated.

 Does the function access another function scope?

As we already discussed function scope, let us shed some light on the question of whether two functions share a scope or not. The answer is no, If we declare a variable in one function and try to access it in another function, it won’t be accessible. For Example: function firstMessage(){const message="I am first Function"; console.log("Accessing from first function:", message);} function secondMessage(){ firstMessage(); console.log("Accessing from second function",message);} secondMessage(); In this example, we constructed a function with the name of firstMessage and declared a variable, after which we console.log it. After that, we constructed a second variable and called the firstMessage() function. It will run fine and we will be able to see the message for the console from the firstMessage() function. However, when we try to access the variable message from the firstMessage() function in secondMessage() function we will see an error. This error is solved by closures.

 What is closure?

If you have ever created a function within another function, you have basically created a closure. The inside function is called closure and a more technical definition would be that a function having access to the parent function scope even when the parent function has closed is called a closure. Let’s discuss an example of a closure: function parentFunc(){ let nameParent="parent"; console.log(nameParent); function childFunc(){ console.log("Child and ", nameParent);}return childFunc;}const store = parentFunc(); console.log(store); store(); In this example, we constructed a parentFunc and initiated a variable nameParent. After that, we console.log the nameParent and constructed a second function within the parent function i-e childFunc. In this child function, we console log a string “child and” with the nameParent variable. We can see that parentFunc returns the childFunc. Now when we call the parentFunc console log will show us only the nameParent. The childFunc wasn’t called and didn’t come into action. However, the outside and the inside function is stored inside the variable store. When we console log the store, we will see both the functions. When we call the store(), we are in fact calling the inside function or the anonymous function that is chidFunc inside the parentFunc(). Now, we will see the inner function console.log i-e “Child and parent”, The closure we created lets us use the scope of the parentFunc as well.

 Conclusion

In this article, we discussed the concepts of scope and closure and in scope, we discussed the two main types of scope that are: global scope and local scope. Further in local scope, we discussed functional scope and block scopes along with examples. After that, we stumbled upon a problem that has access to another function scope. We solved this using discussing closure along with examples.

How to enable JavaScript on Mac (Safari)

Web developers used JavaScript to download and make the content of websites more interactive. JavaScript allows websites to load their pages dynamically and efficiently and send the content of web pages without loading the page. In this modern era, JavaScript makes web pages interactive and adds dynamic behavior to them. Almost every other browser supports JavaScript and has it enabled by default. If you want to prevent attacks from hackers then you have to disable JavaScript but you would not be able to achieve many of the website’s functionalities like animations and many more. If JavaScript is disabled then most of the websites might not give its 100% functionality and also in some cases you might not have access to the content which we are used to. JavaScript used in websites provides numerous features like animations and sounds which make the users more engaged towards it. JavaScript is enabled differently on mac by different browsers. If you can’t observe the changes even after enabling JavaScript then you should restart the browser. Enabling JavaScript allows third parties to monitor your activities so there is more risk of viruses being injected into your machines. Safari has the easiest process to enable JavaScript on Mac. If you want to enable JavaScript on Safari then you should follow certain steps.

 Open Safari

In this step, you have to open Safari on your Mac. Once you open the Safari window then you have to click on the Safari from the top toolbar as shown on the left side of your machine. When you click on it then various Safari options will be shown to you in the dropdown menu.

 Select Option from Safari

After clicking on Safari then you have to click on the Preferences option or press “command+,” keys:

 Select Option from Preference

When you click on Preferences, the following window will be shown. This window has numerous options like General, Tabs, AutoFill, and many more at the top. Then you have to click on the Security Option from various items.

 Toggle Web Content Option

After clicking on the Security option the following window will be shown to you. Now you have to toggle the checkbox of Enable JavaScript. If the checkbox is already checked then it shows that JavaScript has already been enabled on your Safari and vice versa.

Close Preferences Window and settings will be saved automatically

Now you successfully enabled JavaScript on your Mac. Now you just need to simply close the preferences screen and start browsing again.

 Conclusion

This article is about enabling JavaScript on Mac. So, first, we discussed how JavaScript is useful in websites, then subsequently we discussed the steps to enable JavaScript on the default browser of Mac. Illustrations are also provided for each step to help you understand.

How to enable and disable JavaScript in Firefox

JavaScript is one of the popular programming languages that is not just restricted for building web pages but also mobile applications, network applications and web based games. JavaScript makes the web pages interactive and adds dynamic behavior to it through form validation, animated videos and navigation bars. Nowadays almost every other browser supports JavaScript and has it enabled by default. As we know that JavaScript makes your website interactive and various functions are possible through JavaScript so if you disable JavaScript on your browser they may not function as they are supposed to. In this step-by-step guide we will discuss how to enable and disable JavaScript on Firefox which is one of the most popular browsers out there.

 Why Disable JavaScript?

There can be many reasons why a user wants to disable JavaScript in a browser. The reason could be related to security because disabling JavaScript also decreases the risk of downloading malware, to troubleshoot a problem based plugins or browser crashes.

 How to Disable JavaScript in Firefox

Disabling JavaScript is the easiest task, the steps involved in disabling JavaScript from Firefox browsers are provided below along with images which you can follow easily. Step 1: In this first step you just have to open the firefox browser: Step 2: Now that the browser is opened go to the address bar and there you’ve to type “about:config” as shown below and press Enter. Step 3: This will show you a message as shown below, in this you just have to click on the “Accept the Risk and Continue” button provided at the button of the page. Step 4: Now a search bar will be loaded on your screen and in that search bar you’ve to type “javascript.enabled” and press Enter. Step 5: After you’ve pressed Enter, a search for javascript.enabled will be shown along its “true” value. Here you’ve to select the toggle button present at the right to change the value of javascript.enabled to false. Before: After: Step 6: Now JavaScript is disabled on your Firefox browser and you can verify it by using the website, as shown below:

 Firefox with Disabled JavaScript:

 Firefox with Enabled JavaScript:

You can clearly see the difference JavaScript adds to a website and how it adds “life” to it.

 How to Enable JavaScript in Firefox?

To enable JavaScript on Firefox you simply have to follow all the above steps and for the javascript.enabled you’ve to change the value from “false” to “true”. In this way JavaScript will be enabled on your Firefox browser.

 Conclusion

JavaScript is being used everywhere whether it is website development or game development. It adds dynamic behavior to the websites and makes them more interactive. Though disabling JavaScript obstructs website functionality and even makes them look lifeless but to troubleshoot some problems developers usually use this technique. In this guide we discussed how to disable JavaScript on Firefox browser in a step by step procedure, and how to follow all these steps to enable it again. Developers should know how to enable and disable JavaScript in different browsers as it helps them solve various errors easily.

How to enable JavaScript on Chrome?

JavaScript is one of the most well-known scripting programming languages that can be used/utilized on both the client and server sides. The basic function of JavaScript is to make our web pages interactive. Most front-end programmers learn JavaScript. Front-end developers start learning JavaScript after HTML and CSS. Our website is structured using HTML(HyperText Markup Language), CSS is mainly used to give style to our webpage, and JavaScript adds actions or behaviors to our webpage by converting them from static to interactive ones. It is also worth mentioning that JavaScript can alter or update HTML as well as CSS. Now we have learned what JavaScript is. Let’s explore how to enable JavaScript on our browser. But before that we should know why we need to enable JavaScript on our webpage:

 Importance of JavaScript in Web Browsers

The answer is simple. As we saw, JavaScript makes our web pages interactive. It includes animations, web games, and whatnot. When we enable it on our browser we will make our browsing experience enhanced and enjoy all the interactive elements and animations JavaScript offers us.

 Enabling JavaScript on Chrome

JavaScript is enabled by default in Google Chrome however to be on the safe side, we’ll take you through some steps that will enable it on our Chrome browser. Step1: Click on the three black dots set vertically in the top right corner of google chrome. Drop down menu will be opened containing multiple options: Step2: In the drop-down menu navigate to the “settings‘ option and click on it. You will be directed towards the settings screen. Step3: Here you will be able to search the search bar which is present at the top of your webpage. It will be labeled as “Search settings”. Search “Javascript” in this search bar. Look for “Site Settings” once you are finished typing. Click on it: Step5: After clicking on “Site Settings”, find JavaScript. Site settings contain many permissions which you can update. Simply scroll down to “JavaScript” and click on it. Step6: Now you need to enable JavaScript. The option for this is available at the top. You’ll see either label of “Allowed(recommended)”. When you enable it, all the web pages you visit will have JavaScript enabled. If you don’t see the label “Allowed (recommended)” then two radio buttons will be present. The first radio option will say “Sites can use JavaScript” on which you have to click or select: However, it should be noted that you can block or allow only some web pages. This option is available here after the labeling “Allowed”. Now that you have enabled JavaScript, you can close the settings tab.

 Conclusion

We learned how to enable JavaScript in Google Chrome in this tutorial and we also discussed why it’s important to have JavaScript enabled on Google Chrome. Without enabling JavaScript our web pages will be kind of dull and we won’t be able to do much work as our webpage will not be interactive hence making it important to enable JavaScript on Google chrome.

How to disable JavaScript in Tor

Javascript was first introduced in 1995 and it is one of the most popular computer programming languages that is lightweight and dynamic. Lightweight means easy to implement as well as minimalist features and syntax. JavaScript is used to create web applications or web pages and is used by 95 percent of websites in the world. JavaScript is so popular because of its simple and intuitive syntax as well as being easily implementable and supported by HTML. Tor is a browser that is getting popular day by day and was originally developed in the mid-1990s for the purpose of communicating in an anonymous and secure manner. Nowadays, people use it for exactly the same reason ie to keep their privacy and anonymity on the browser. Tor is also called an Onion router. With Tor, we can browse the internet anonymously as it involves a number of volunteer relays that ensure the bouncing of internet traffic and guarantee that the user browsing is not monitored.

 Why is it important to disable JavaScript?

It is important to disable JavaScript in Tor for many security reasons as the Tor browser’s earlier versions were vulnerable to JavaScript attacks because JavaScript provides a backdoor to the hacker or attacker from which the attacker can track the user using the user’s provided session details. It happened back in 2013 where hackers took advantage of the Noscript feature being disabled in the Tor browser and extracted users IP addresses and Mac addresses.

 Disable JavaScript in Tor browser?

Now that we know why disabling JavaScript is important let us continue and go through all the steps to actually achieve our purpose of disabling JavaScript in the Tor browser: Step1: Open Tor Browser Step2: Click on the menu symbol or hamburger icon located at the top right corner of the Tor browser: Step3: When you click on the menu bar symbol a menu will open as shown in the above screenshot, after which look for options and click on it. Step4: Now the settings tab will open where you have to open up the “privacy & security” settings by clicking on the “Privacy & security” option from the left menu bar of the viewscreen: Step5: When you click on Settings and privacy, scroll down until you find security option: Step6: Click on the safest option and JavaScript will be disabled. You have successfully disabled JavaScript on the Tor browser.

 Conclusion

Tor is one of the most sophisticated browsers that lets users surf the internet anonymously. Disabling or turning off JavaScript in Tor Browsers is necessary because of the prevention of JavaScript exploits. In this post, we have provided a simple, easy to understand and step-by-step guide on how to disable JavaScript on Tor Browser. We hope that this article proves to be informatively beneficial for you and now you have successfully disabled JavaScript on the Tor browser.

How to disable JavaScript in Google Chrome

JavaScript is considered to be one of the most popular and widely used languages. JavaScript is a popular computer programming language because of its simple and intuitive syntax as well as being easily implementable and supported by HTML. Almost every other browser supports JavaScript and has it enabled by default. If you want to prevent attacks from hackers then you have to disable JavaScript easily. Javascript can be disabled from operating in a browser. This is probably because of security reasons. There is always a security risk since the code is generated by a computer. The process can be infected. Another reason not to use Javascript is the malfunctioning of many sites and crashing the browsers. Disabling javascript can prevent the browser from crashing. While administering the site, Javascript needs to be disabled to prevent any troubleshooting. For instance, while using content management, you need to first disable the javascript code or plugin extension to diagnose and fix the issue.’ This article provides you a step-by-step guide on how to disable JavaScript in Google Chrome which is one of the most popular browsers out there. You have to follow only a few steps and then you will be able to disable JavaScript in Chrome. Below we are going to demonstrate each step visually.

 Method 1

First step is to open the dev tools in chrome. You can open dev tools by following ways. First possible way is that you can open it by pressing CTRL+SHIFT+I. The second possible way to open dev tools is that you must first open google chrome and then click on the main menu button which is at the top of the page as shown in the picture below. Then move down to the more tools option then select Developer Tool. After successfully opening the dev tool, you have to open the command menu by pressing CTRL+SHIFT+P. The following picture shows the command menu. Now you have to write JavaScript in the bar of the command menu as shown in the picture below. Subsequently, choose the option i.e. “disable JavaScript” from the list and then press enter. Now you have successfully disabled JavaScript for your Chrome browser. The warning icon beside the source will assure you of a JavaScript disability. JavaScript will be disabled until the dev tool is closed. JavaScript will remain disabled even when you reload the page.

 Method 2

The first step is to open Google chrome, click on the main menu button which is at the top of the page, and select the settings option as shown in the picture below: Subsequently, chrome settings will be opened as shown in the picture below. Navigate down the page up to the “Privacy and Security” panel and select site settings as shown below. After selecting site settings then you will see the following interface as shown below. Navigating down the page up to the “Content” panel. Then select the “JavaScript” option. After selecting JavaScript a new window will appear as shown below and you have to toggle the option “Don’t allow sites to use JavaScript”. Now you have successfully disabled JavaScript for your Chrome browser.

 Conclusion

JavaScript is versatile and you can easily learn it and then become a master of this programming language. This article explained a simple step-by-step guide on how to disable JavaScript in Chrome. Subsequently, we discussed two methods to disable JavaScript in-depth. Illustrations are also provided for each step to help you understand.

Array Manipulation Methods- working with arrays

Arrays are the fundamental part of JavaScript and in this post, we are going to talk about arrays manipulation. Array manipulation is the task that helps us add/remove/transform elements in our array. There are dozens of methods which help us manipulate arrays according to our needs.

 What is an Array?

The array is a type of variable which is structured in a way that we can store multiple and different types of values in just one variable and later access those values using array indexes. Index is the position number where the array element is stored or saved. For Example: const leagues=["Laliga","Premier League","Bundesliga","Serie a"]; In the above example, if we didn’t use arrays then we would have to declare 4 variables and initialize them with the above values which would have been too hectic. For example: const league1="Laliga";const league2="Premier League";const league3="Bundesliga";const league4="Seria a"; As we can see, it’s much better that we use arrays than traditional methods. If you are still not convinced, then suppose you had to list all the major football leagues in the world. Would you declare all the variables and initiate with the football league names one by one. Wouldn’t it be better to use arrays? Indeed it is.

 JavaScript Array Methods

Converting Arrays to string

Let’s say you have an array that you’d like to convert to a string for which JavaScript provides us the toString() in-built method to aid us. The toString() method will convert our array to a string. All the array values will be separated by a comma in the string Example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"];//converting to string console.log(leagues.toString()); The next inbuilt method used a lot by developers is the join() method. This has the exact same function of toString() i-e converts an array to string. The only difference in the join() method is that here we can specify the separator. For example, in place of commas, we can put a full stop. For Example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"];//converting to string with . separator console.log(leagues.join(".")); Here we specified that the values of an array should be separated with full stop when the array is converted to a string.

 Push and Pop

When working with arrays as a developer, there will be times when you need to add or remove items from an array. To achieve the task of adding something or removing something from an array we use the pop() and push() method.

Pop() Method

Deleting a value from the array is achieved by the pop() method and it deletes the last index value from the array. For example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"]; console.log(leagues.pop()); console.log(leagues.toString()); As we can see in the screenshot of the console that the pop item was on the last index and after that when we console log the array there was no Seria a.

Push() Method

Push syntax is the same as pop. The difference is the function each performs. The push() method is used to insert or add elements at the last index of the array. For Example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"]; leagues.push("Ligue1");//converting to string console.log(leagues.toString()); In the push() method argument we pass the value we want to add to the array. In this example, we passed “Ligue1” as we wanted to add that to our array leagues. When we push the value then we will see Ligue1 at the end of the array.

 Shifting Elements

The Shift() method is the same as the pop() method except that it removes the first element from the array. It does this by shifting all the other elements to a lower index except the first. It removes the first index element. For Example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"];//removing first element console.log(leagues.shift());//converting array to string console.log(leagues.toString()); In this example, in the console window, we will be shown the element that has been deleted from the array. Then the new array will be shown. The unshift() method is the same as the push() method except that it adds an element at the start of the array. The syntax is the same as the shift method i-e leagues.unshift(“Scottish League”).

 Changing Elements

We can change an element at the specific index. Index starts from 0 in an array. For example, we can change the first element by: leagues[0]="Scottish League"; We can also find out the total length of the array by using the built-in length method of JavaScript. //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"]; console.log(leagues.length); Output: 4

 Splice() Method

The Splice() method is used to add items to an array just like the push() method. For Example: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"]; leagues.splice(2,0,"Ligue1");//converting array to string console.log(leagues.toString()); Splice takes an index where you want to add an element. In this example, we specified the 2nd index where we want to add “Ligue1”. The elements we want to delete from the array are given in the second argument. After this, we can add new elements, as much as we want. The output will be: We can also use the splice method to remove a value at the specified index. ForExample: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"]; leagues.splice(0,1);//converting array to string console.log(leagues.toString()); It will remove the element that is at the first index.

 Merging Arrays

We can also merge arrays using the concat() method. The concat() method does not alter the original array and only creates a new array. For Example: In this example, two arrays will be combined using the concat() method: //array having the name of soccer leaguesconst leagues=["Laliga","Premier League","Bundesliga","Serie a"];const lowerLeagues=["Scottish","Australian"];const newTotalLeagues=leagues.concat(lowerLeagues);//converting array to string console.log(newTotalLeagues.toString()); We added the lowerLeagues to leagues.

 Conclusion

Multiple data elements or variables of the same kind are represented in a single name array and that array can then be manipulated in many ways which are discussed in this post. We discussed array manipulation by going through the most common methods of how to manipulate an array. We hope that all these examples would have given you an idea of how array manipulation works.

Fun, Easy and Cool JavaScript Projects

There was a time when JavaScript was only associated with websites but those days are gone and JavaScript has made its way into the tech world. From mobile applications to server based applications, everything has JavaScript involved in them. With so much popularity, it has become an important language to learn and if you’re a beginner at it then the best way of learning a language is by creating various small level projects. Such projects help beginner level developers to understand the core concepts easily and helps them become masters of the language. That’s why in this article we’ll discuss various fun and easy JavaScript projects that you should definitely try to build.

 JavaScript Calculator

One of the best and cool ways to get started with any programming language is by creating a Calculator. There are various ways we can make it interesting by adding complex features, but if you’re a beginner start with the simplest functions like Addition, Multiplication, Subtraction and Division. Firstly create a clean and cool interface using HTML and CSS and then add the functionalities using JavaScript. You can make it more complex with time and practice.

 JavaScript StopWatch

Another simplest and easiest project you can do within a day is building a stopwatch using JavaScript. The stopwatch doesnt require alot of features, so not much time is required coding it. The interface can be made cool and modern using CSS, and further functionalities like Stop, Start and Rest can be added using JavaScript. It’s the easiest project which will help you understand the concepts of JavaScript much better.

 Hangman Game using JavaScript

Now if you’re looking for a bit of a challenge and want to build something interesting, then a game should be the best option. There are various games you can build but the best one is to start with Hangman. It’s a guessing game where users have to guess the word letter by letter, where the guesses are limited and when the guesses run out the game is over. This might take you some time if you’re a beginner but if you’ve good understanding of JavaScript then you can complete it easily. You can create the interface with CSS and then add functionalities like limit of guesses, displaying of the number of guesses left and taking the guesses of the user as input through JavaScript.

 Tic Tac Toe using JavaScript

Another interesting and fun game that various people build if they’re beginners at a language is Tic Tac Toe which can be completed within a day. The game seems extremely simple but the logic isn’t that simple as we think because we’ve to create a logic that follows all the rules of the games using JavaScript. Start writing logic on a paper, divide it into steps and then implement that logic into your code. Make the interface modern using CSS and you can make the game complex by dividing it into various levels for users.

 Guess the Color using JavaScript

Another cool and easy game idea for beginners is a simple Guess the Color game using JavaScript. The game will display a RGB value of a particular color with various color options being displayed to the user from which they’ve to choose the particular color that they think matches the RGB value. It’s a simple game which you can make more complex by limiting the number of guesses users have or you can add life lines which decrease with each wrong guess.

 Weather App using JavaScript

To make the project more complex and interesting for you that involves the use of various APIs then the best option is Weather App. This project might take some time but will look amazing on your portfolio as well as improve your skills. You will understand how to pull data and display on your webpage using APIs, and you can make the interface more interesting with CSS, as well as you can use form validation if you want users to have a profile of their own.

  Do List using JavaScript

Another best quality of JavaScript is that you can code dynamic lists with it where users can edit, delete, add and move items and make it visually appealing through CSS. So another exciting yet simple project would be creating a to-do list with JavaScript and making it look even cooler by introducing drag and drop features where users can move items between various lists.

 JavaScript Clock

Building a clock in any programming language is the easiest project that will help you understand the concepts of the language even more. To practice more about variables and loops you can build a digital clock where you can further make it complex by adding functionalities of stop watch, reminders etc and use CSS for an aesthetically pleasing interface.

 Conclusion

JavaScript is emerging day by day and it’s a good time to learn and become a master of this programming language as it’s being used almost everywhere. To get better at this language it’s a good start to create small projects that are easier to build but make you understand the concepts easily. In this article we provided you ideas of various projects that you can get started with using JavaScript and build your skills and understand the concepts much better.

Fetch vs Axios – Which should I use?

Web applications use the HTTP protocol to communicate within servers. Fetch and Axios play a significant role in making HTTP requests to receive information from servers and perform distinct tasks. The best thing about Fetch API is that it can be easily accessible across all browsers and is also able to reproduce features of Axios. If we talk about usability then we say that Axios is best over built-in APIs. In this article, we first go through what Fetch and Axios are, then we explore features of Fetch and Axios, then compare them in-depth to completely comprehend their advantages.

 Fetch

Fetch is an API that generally provides you an easy method that helps to manipulate and fetch requests across the server. You can easily define the Fetch() method on the window object. Fetch API uses the interface of JavaScript to manipulate and access HTTP requests. Nevertheless, it is necessary to know that it takes a single essential argument i.e. the path of the URL which you want to be fetched, and return a Promise accordingly. If you want to retrieve the request’s response then Promise is used. Following are the features of the Fetch() method: Capable to control cache Ability to redirect controls Able to fetch and read data without streaming efficiently The basic syntax of Fetch() API is shown below: fetch('path which you want to be fetched') .then((response) =>{ // in this section, you have to write code that handles response}) .catch((error) =>{ // in this section, you have to write code which handles error});

 Axios

Axios is a library of JavaScript which either works to make HTTP requests through node.js or to make XMLHttpRequests through browsers. Promise API is reinforced by XMLHttpRequests. Axios has the ability to perceive the request and responses as well as also enable the protection against XSRF. Axios is also capable of canceling requests efficiently. Following are the features of Axios: Capable of intercepting requests and responses Also has built-in download progress Ability to convert requests and responses automatically Able to cancel requests Protect client-side against XSRF The basic syntax of Axio() API is shown below: axios.get('url') .then((response) =>{ // in this section, you have to write code which handles response }) .catch((error) =>{ // in this section, you have to write code which handles error })

 Fetch Vs Axios

Fetch and Axios are not as simple to compare as you think. If we talk about the compatibility of browsers then we say that Axios is more preferable as compared to Fetch. Fetch only supports few browsers i.e. Edge 14+, Chrome 42+, Safari 10.1+, and Firefox 39+ whereas Axios supports some old browsers such as IE11. Axios is best suited in terms of the transformation of data as it transforms data of JSON automatically whereas fetch requires two steps for the transformation of JSON data. If you want to transform JSON data using the Fetch API, then first you have to make a request then in response, a JSON function is called. Axios has a built-in feature to protect the client-side while Fetch does not have this feature. Furthermore, Fetch does not take URLs in the object of request while Axios does. Axios permits to cancel requests timeout immediately and also intercept requests of HTTP whereas fetch does not. In Axios, data property is used and data has an object. On the contrary, fetch supports the property of the body. Last but not the least, the installation of Axios is simple and it supports old browsers as well while installation is not required in fetch and cannot support old browsers. Moreover, Axios also has a built-in feature to download progress whereas fetch does not have this feature.

 Conclusion

As discussed above, Axios is an easy-to-use and compact API used for the communication of HTTP requests. One of the best things about Axios is that it intercepts requests timeout automatically but for Fetch() you have to set requests timeout. Furthermore, if you want to modify the logic of code then you have to override the function of Fetch() which increases the complexity of the code. As you can see, both have different aspects in terms of response time, the transformation of data as well as syntax. After analyzing the differences between Fetch and Axios, it concludes that Axios is a more preferable and easy approach than Fetch while sending HTTP requests.

Debugging JavaScript code

No matter how much of an experienced developer you are, you’ll encounter errors. It’s just human nature to make mistakes. Sometimes we make a syntax error or some logical error. No matter what the error is, you want to fix it as soon as possible. Debugging is this process of finding errors and fixing them when you examine your code or program. While JavaScript is said to be difficult to debug, we will make your lives easy. Today in this article we will talk about how to debug JavaScript code.

 JavaScript Debugger

All modern browsers have in-built JavaScript debuggers. These debuggers assist us by showing those errors. These debuggers can also be turned on or off depending on our needs. The interesting thing about these debuggers is that with this we can also set breakpoints. Breakpoints are placed in our code where we stop the execution of the code. When the code is stopped, we can check for the errors and examine the variables. As Google chrome is a very famous browser, we will use chrome for most parts of this article. However, in the end, we will show you how to enable JavaScript debugging in other browsers as well. To start debugging in google chrome press the F12 key. We can also press CTRL+SHIFT+I to open the debugger. However, even if these two don’t work, then try right-clicking from your mouse anywhere inside your browser tab window. Click on inspect and after that go to the console.

 Using console.log() Method

Google chrome supports debugging hence we can use console.log() in our JavaScript code to display it inside our console window. Example const str = "let's debug in console";//let's view this in console window console.log(str); Now when we click F12 and go to our console we will see:

 How to set breakpoints

We can also set breakpoints in the debugger window. Like mentioned earlier, with every breakpoint we set, the code execution will stop. We will then examine our code and find the error. If we didn’t find the error in that breakpoint, we will add another breakpoint. It is very easy as we can continue the execution code with just a click button (normally play button). Suppose we have a button. Every time we click the button it adds a value to the previous value. The default value will be 0. Now if we want to debug this using breakpoint we have to set a breakpoint. If the counter value is not increasing with the click we know that the problem is on the event listener click. To put a breakpoint on the event listener, click F12. This will direct you to the console window. On the console’s side, click on the sources tab and then proceed to the breakpoint for event listeners. In this click on the mouse events and then tick the click option. Congratulations you have set your first breakpoint. Whenever you execute the program, it will stop at the mouse event listener click event. We can resume it by clicking on the resume button at the top of the sources tab. HTML: <body> <button id="btn">0</button> <script src="code.js"></script></body> JavaScript: const btn=document.getElementById("vanish-btn"); let value=1; btn.addEventListener("click", function(){ btn.innerHTML=value++;})

 Using Debugger Keyword

It is the same as the breakpoint explained earlier except that it is done through JavaScript code and not manually. We use the debugger keyword whenever we wish to debug a code. Debugger keywords basically stop the flow of execution of code just like a breakpoint. After stopping the execution, it calls the built-in debugging function. This debugger function works the same as a breakpoint. Suppose we want to add two variables. However, before displaying them as an alert, I want to debug them. The following code will provide the solution for this: let num1=5; let num2=10;debugger; alert(num1+num2); The debugger keyword forces a breakpoint or stops the execution of the code and invokes the debugging function. If any debugging is required, the debugger function is called; otherwise, nothing is done.

 Debugging in different browsers

The common practice to start debugging is by clicking on inspect or pressing the f12 key in your browser. However, if that doesn’t work, follow the below commands to open the debugger menu.

 Google Chrome

Click on the menu button on the top right corner of google chrome Click on more tools Click on developer tools Select console or sources according to your need

 Mozilla Firefox

When you open the browser, click on the menu After that click on web developer Click on the web console

 Microsoft Edge

When you open the browser, select developer tools from the menu Then select console

 Opera

Open browser Select menu and then the select developer Now select developer tools Then click on the console

 Safari

Go to the main menu and click on Safari preferences Click on the advanced option In the menu bar, select Enable show develop menu. When develop is seen in the menu click show error console.

 Conclusion

There are many debugging methods available. We explained the most used/common and easy methods to debug our JavaScript code. With developing you will need to debug again and again. I suggest you save this article as a bookmark in your browser so you don’t have to search again and again.

What are Callback Functions?

If you’re a programmer, you’ve probably heard of functions, which are a set of statements that perform an action and return an output but what are callback functions? The callback function is an extremely important concept of javascript and is widely used in promises, event listeners, arrays, and much more. We’ll go over what callback functions are and how to use them in this tutorial as well as We will also talk about the synchronous and asynchronous callback functions. To have clear and profound concepts of Callback functions we will implement some examples as well.

 CallBack Function

A callback function is a function that is first passed as an argument to some other function and needs to be executed after the statements written in that function definition and as the name implies, it is run later within the function. To put it in simple words, a callback function is executed once the current effect is processed.

 Syntax for writing a callBack function

The basic syntax is: function nameFunc(callbackFunc) { callbackFunc();} This is a ‘nameFunc()’ function that takes a ‘callbackFunc()’ function as an argument. The ‘callbackFunc()’ function is called from within the ‘nameFunc()’ function so it is a callback function indeed.

 Example1

Suppose we want to console.log a message after 2 sec. function message() { console.log("Hello world after 2 seconds");} setTimeout(message, 2000); The setTimeout() function is a built-in method of JavaScript that takes a timer and a callback function as an argument. Now the message function(a callback function) will only be called and get executed when the timer will expire. In the above code, the function message() is passed as an argument and it is called after 2000 milliseconds (2 seconds). Now to relate this to the call back function, the message() function was called after 2 seconds. It wasn’t executed before those 2 seconds. Hence it is a callback function.

 Need for callback functions?

You must be thinking why do we even need callback functions. The answer is simple. JavaScript is a sequential or single-threaded language which means it executes sequentially line by line. JavaScript doesn’t wait for a response before moving on to the next line. It will keep executing and listening for other events or lines of code.

 For example:

 Example2

Suppose we are logging 1 and 2 from two different functions to the console: function firstMessage(){ console.log("1");}function secondMessage() { console.log("2");} firstMessage(); secondMessage();

 Output:

12 As expected, the function firstMessage() is executed first and then the secondMessage() function is executed.

 Example3

Suppose that the firstMessage() method comprises an API request to retrieve data from a server. We’ll have to wait for the server’s answer/response hence let’s utilise the built-in method setTimeout once more. This time we’ll delay the request by 3 seconds to see how we can request an API fetch request. function firstMessage(){ //timeout function for delaying request setTimeout( function(){ console.log("1"); }, 3000); }function secondMessage() { console.log("2");} firstMessage(); secondMessage(); In this code, we just moved the console.log(“1”); inside the setTimeout() function. Now what’s really interesting is that when you run this code, you’ll see that the 2 will be shown first in the console: After 3 seconds the 1 will be shown: As we can see, the firstMessage() function was called first and then the secondMessage() function was called. However, we cannot see the result in the sequence we called our function. It’s not that JavaScript did not return our code sequentially, it’s just that JavaScript did not wait for the firstMessage() function to execute completely and started executing the secondMessage() function. This example was solely put here to show you why we need callback functions. Callback functions let us make sure that some code will not execute until our required code has been executed.

 Callback function types

Now that we have seen what callbacks are, how they are used, and why they are important, let’s look at the two types of callback functions.

 Synchronous callback function

Synchronous callback functions are run/executed at the same time as the higher-order function which is using the callback function and is mainly blocking; it completes its task then gives the control to another function or line of code. This is beneficial as suppose you are fetching items from an API. You want your page to load once you fetch some data from an API. Unless the response from the API is fetched, the whole site has to wait. Example 2 stated above was synchronous functions as it executed line by line and once the first function was executed only then the control was given to the second function i-e secondMessage() function.

 Asynchronous callback function

Asynchronous is completely opposite of synchronous as it works parallel with the caller of the function and the call back function. Asynchronous functions are non-blocking as they run or execute later than the higher-order function. Example 3 provided above was an asynchronous callback function as we called the firstMessage() function but it waited for two seconds. In those two seconds, it gave the control back and the secondMessage() function was executed. Once the three seconds time was up, the firstMessage() function started executing again.

 Conclusion

A callback function is a function that is first supplied as an argument to some other function and needs to be executed after the statements written in that function definition. We learned what callback functions are and how to use them, as well as why callback functions are important and what the two types of callback functions are in this post.

What Does the “use strict” Directive Do

JavaScript evolved for a long time having no compatibility issues and modified by adding new features but not changing the old features. It had its advantages and disadvantages and the advantage was that it didn’t allow the breaking of the existing code, however, the disadvantage was that any error made by the developers or creators was stuck within JavaScript forever. It carried on until ECMAScript 5 (also referred to as ES5) was introduced in 2009 whose perk was that it added new features while modifying current ones. However, by default, these modifications are off. One needs to enable it with a special message or command which is the “use strict”.

 What is “use strict”

The basic definition of “use strict ” is that it enables JavaScript to run code in strict mode. Strict mode is something where one cannot use undeclared variables. Strict mode also helps us avoid possible bugs/errors, if we have not properly followed JavaScript syntax. It also helps us when we make typos which results in an unwanted new variable. We can also say that the basic purpose of strict mode is to make our code look cleaner.

 Universally supported?

It should be kept in mind that use strict is not universally supported by the browsers. Most modern browsers support “use strict” with the exception of Internet Explorer 9 and the versions below 9. The following browsers with versions above or the specified versions support “use strict”.
Mozilla FirefoxInternet EdgeGoogle ChromeOperaSafari
4.010.013.012.16.0

 Strict Mode Syntax

We can implement or declare use strict by adding at the top of a function or code the keyword “use strict” in an exact manner. If we declare it at the top of our code, it will have a global scope which means all our JavaScript code will execute in strict mode. Let us see two examples. In the first example, we will use an undeclared variable without using “use strict”. In the second example, we will use strict mode in the same manner.

 Example 1:

name="Linux Hint"; console.log(name);

 Output: Linux Hint

 Example 2:

"use strict"; name="Linux Hint";//this will cause an error that name is not defined name is not defined” error will be caused in the above scenario. Let us have a look at another example where strict mode is used inside the function. “use strict” scope will be functional i-e limited to the function.

 Example 3:

function myFunc(){ "use strict"; y=4; //this will cause an error //error will be that y is not defined} myFunc(); In this example, the first variable “name” will not have an error as we are not using strict mode. However, in the function, we will be shown an error of “y” is not declared as we are using “use strict” mode. Let me stress again that in this example the strict mode scope is restricted to the “myFunc()” function.

 Why use Strict mode?

Now that we have looked at the syntax of the strict mode and some examples, let us explore the question of why use Strict mode? The perk of using strict mode is that it makes our code cleaner as mentioned earlier. Also, Strict mode helps us write secure JavaScript. Often we ignore bad syntax. This can cause us problems later. Strict mode aids us in converting informal/bad syntax code into real errors so that we can handle them accordingly. In example 1, we saw that we didn’t declare a variable but the JavaScript console didn’t throw any errors. It treated the variable “name” as a global variable. In Strict mode, we avoid this as strict mode throws an error that name is not defined. This helps us avoid accidentally declaring global variables in our code.

 Restrictions in Strict Mode

Let us discuss what is not permissible or not allowed in strict mode. We can see from example 1 that we cannot use a variable in strict mode if it is not defined or declared. The same goes for objects. We have to declare objects in strict mode otherwise we will get an error.

 Example 4:

"use strict"; language={ first:"English", second: "Chinese"};//this will throw us an error as object "language" is not defined Strict mode also doesn’t let us delete a variable or a function.

 Example 5:

"use strict";const pi=3.143;delete pi;//this will cause an errorfunction myFunc(){ //Hello World}delete myFunc;//this will cause an error Apart from this, strict mode restricts us from using keywords reserved in future JavaScript versions or currently using. For example, we cannot use implements, let, package, interface, yield, static, protected, public, private, arguments, etc.

 Keyword “this” in Strict Mode

Keyword “this” is used to refer to an object it belongs to. “this” keyword behaves differently in strict mode. Suppose you use an undeclared object with the use of “this”. JavaScript will return “undefined” in strict mode rather than the object.

 Example 6:

"use strict";function myFunc(){ alert(this); //this will show us an alert of undefined}//calling the function now myFunc();

 Conclusion

The keyword use strict helps JavaScript developers to run their JavaScript code in strict mode hence restricting the use of undeclared variables and helps developers by avoiding possible errors or bugs. We studied the “use strict” directive in this post and discussed how and why to use the “use strict” directive as well as discussed, the browser that supports strict mode. We held a grip on the concepts using examples. By studying this article, we know how to make our code cleaner and how to avoid unnecessary global variables with the use of “use strict”. Let me stress on the fact again that if you are working with “use strict” always declare it at the top of a block of code or top of the function for it to work.

Top 10 Popular Websites Built using JavaScript – Examples

Popularity of JavaScript is increasing day by day with it’s usage for building websites, mobile applications, web based games and server side applications. It’s a client side scripting language but with the introduction of NodeJs, it’s now possible to handle server side as well. JavaScript is evolving everyday, making it’s way more into the tech world by introducing various frameworks, which makes the life of developers easy. Many websites which are popularly known are built around JavaScript which shows how important and useful the language is. In this write-up, you will have the top 10 popular websites built using JavaScript.

 Google

The most popular search engine that we all use on daily bases and that makes our life easier, has used JavaScript for building not only its front-end but backend as well. Google plays a huge role in everyone’s lives, and the very common phrase “Just Google it” is on our tip of tongue whenever someone asks us a question. Google uses various tools of JavaScript such as Closure tools in Google Docs, but the developers of Google also create its own open-source JavaScript tools such as AngularJs. Moreover, The popular Google browser Chrome uses JavaScript engine V8, which was created by Google, and it also plays a major part in NodeJs, so we can say without Google there would be no Node.

 Youtube

Another popular website built around JavaScript that is used by billions of users everyday is Youtube which helps people to watch, share, record and upload videos. Everyday we see various well known people start off their journeys from Youtube platform, through which they change people’s perspective regarding ways of earning. Youtube has become a career-path for a huge audience and people don’t see it as an application to watch videos, but rather they’re using it for creating content and sharing with their audience. Now if you want a video for educational purposes or cooking related or anything you can think of, a video would be available for it on Youtube.

 Amazon

The largest website that has changed E-commerce for the world is Amazon which uses JavaScript along with other programming languages. It’s an online ecommerce website that is being used worldwide for buying and selling stuff. They’ve categories for everything, from electronics to household, anything that you can think of will be available on the website. Moreover the website uses frameworks of JavaScript such as React and Angular which are popularly being used by developers around the world.

 Wikipedia

The world’s most popular and well recognized encyclopedia on the internet is Wikipedia that uses JavaScript along with other languages. We’ve all used Wikipedia for various educational purposes along with other stuff, as it provides us with a detailed description of the topic that we searched. Wikipedia uses a simple layout without any ads and it’s free of cost. You can search anything and it will provide you with the best detailed results.

 Facebook

One of the most popular social media websites which we all are familiar with is Facebook that is built around JavaScript along with other languages. The importance of JavaScript in Facebook can be understood by the fact that if you disable JavaScript from your browser and try to log in into Facebook, it wont let you in into your account. Furthermore, Facebook created React which is a popular framework of JavaScript and applications like Instagram and Whatsapp are built using this framework.

 Twitter

Twitter is a popular social media site which is not only used by commoners but by the politicians as well. It also uses JavaScript. This website allows users to share their opinion and mostly people use it to be updated about events happening around the world. Its fast moving feed, the sharing of news within seconds and how it allows users to stay connected with the world is the reason for its popularity.

 Netflix

The website that has changed the way we see entertainment is also built around JavaScript. Netflix is being used worldwide for streaming movies, TV shows and even became a platform for content creation. The website uses a distributed approach that divides the interface into individual services and hence speeds up the server. A huge portion of the website is running on NodeJs, which is a runtime environment of JavaScript.

 PayPal

The most popular online payment giant that is available worldwide is Paypal that not only uses JavaScript for its front-end but also uses NodeJs. The website allows users to pay, send and receive the money online without any security issues. They’ve also created KrakenJs which is their version of Express that simply shows how important the role of JavaScript is for the website.

 Uber

The popular worldwide taxi service that has changed the way of traveling within the city is Uber which is built around JavaScript. They’ve various requests coming within seconds, and they need to keep track of each customer’s data, the location of drivers and need to match the request with drivers as fast as possible. All of this data handling is done through NodeJs because of its asynchronous capabilities and has become the center of user facing stack for Uber.

 LinkedIn

The popular social network for professionals is LinkedIn where users create their profiles for finding jobs and hiring skilled people. The website uses JavaScript along with other languages, and makes the interaction of users with others easy. It uses NodeJs for its mobile application which makes the data sharing, and building API easier for the developers and its asynchronous capabilities allows better performance while using lesser resources.

 Conclusion

JavaScript has become the core of various popular websites along with its frameworks that are being widely used. In this article we discussed 10 popular websites which are using JavaScript, and creating their own frameworks with it. The popularity of JavaScript is increasing day by day as it’s making the server secure through its frameworks and providing fast performing websites to its users.

What are JavaScript Object Accessors

JavaScript object accessors are used to access and update the objects and two keywords used for this function are getter and the other is the setter. JavaScript introduced getters and setters in ES5 in 2009. We’ll look at what getters and setters are and how to utilize them in this tutorial as well as go over why you should use get or set methods of JavaScript. Apart from this, we will discuss the object.defineProperty() as well. In the end, we will shine some light on which browser supports the set and get methods. So let’s get started.

 Get Keyword

The get method is used to retrieve a value, as its name implies, and in the technical world, it can be defined as a binder of an object property to a function which is called when the property is wanted. We cannot get the value until we access the get method. However, we define the object’s property beforehand.

 Example:

const player={ name: "Hazard", club: "Chelsea", shirtNo: 10, get clubName(){ return this.club; }}; alert(player.clubName); In this example, we used the clubName property to get the value of the club property.

 Set Keyword

It is the opposite of the get keyword. It is used to set a value. In the technical world, it can be defined as a binder of an object property to a function when we want to set a property.

 Example:

const player={ name: "", club: "Chelsea", shirtNo: 10, //setting a player name set setName(setName){ this.name=setName;; }};//passing/setting the name i-e object property using a setter player.setName="Mount";//lets see the data through an alert alert(player.name); In this example, we created an object first. In that object, we created a set method using set keyword where we are setting the name of the player which is passed to it. After the object, we set the name of the player, and then we displayed the result using an alert.

 Function vs Getters

By now you must be thinking, aren’t they the same, well the answer is yes and no. Let us explain this using examples:

 Example Function:

const player = { name : "Hazard", club : "Chelsea", shirtNo : 10, myFunc : function() { return this.name+" plays for "+this.club; }}; alert(player.myFunc());

 Example Getter:

const player = { name : "Hazard", club : "Chelsea", shirtNo : 10, get myFunc() { return this.name+" plays for "+this.club; }}; alert(player.myFunc); In the function example we are getting the myFunc() as a function i-e player.myFunc(). However, in the getter example, we are accessing the property i-e player.myFunc(). Now we know that the getter syntax is more easy and readable than the function.

 Object.defineProperty()

The JavaScript Object.defineProperty() is used to add getters and setters. It takes three arguments and the syntax of Object.defineProperty() is: Object.defineProperty(objectName, propertyName, objectDescriptor) The first argument is the object’s name, the second is the property’s name, and the third argument is a description of the object.

 For Example:

//define an object const player={ name:"Eden"}//now we get a property of an object Object.defineProperty(player, "getName",{ get: function (){ return this.name; }});//now we set the property of an object Object.defineProperty(player, "setName",{ set:function(val){ this.name=val; }}); console.log(player.name);//let's give the player a full name player.setName="Hazard"; console.log(player.name); In this example, first, we defined an object. After that using Object.defineProperty() we set the setter and getter. Now when we first console.log the player name is “Eden”. But when we set the name using setter the player name changes to Hazard as set by us. It is true that when we use getters and setters, JavaScript secures better data quality.

 For Example:

//creating an object const player = { name : "Hazard", club : "Chelsea", shirtNo : 10, get myFunc() { return this.name+" plays for "+this.club.toLowerCase(); }};// using get display data alert(player.myFunc); In this example, we used the name and club property of the object player. We converted it to upper and lower case and returned that value. The solution looked like this:

 Why use getters and setters?

Can accomplish and carry out tasks behind the scenes. Makes us secure better data quality as mentioned earlier Also has a simpler syntax Properties and methods syntax is similar

 Which browsers support this?

Microsoft EdgeOperaSafariMozilla firefoxGoogle Chrome
9.0 and aboveyesyesyesyes

 Conclusion

We learned almost everything about JavaScript assessors which are get and set methods in this post. Going into a little depth we also explained what Object.defineProperty() is. Apart from that, we discussed the pros of using assessors and which browsers support assessors. By using assessors, a developer makes his code perform actions behind the scenes and secures data. As it has simpler syntax it also makes our code cleaner.

How to Reverse an Array

Reversing an array is a very popular coding problem which is often asked as an interview question when applying for an entry level JavaScript Developer position. Sometimes you will be asked to modify the original array so that the first element becomes the last and the second element becomes the second last element of the array and so on. Sometimes you might be asked to reverse an array without changing the original array. In this post we will look at different methods which are used to reverse an array; these methods will include the methods which reverse the original array as well as methods which can be used to make a new reversed array.

 How to use the JavaScript reverse() method

The reverse method is used to reverse the indices of the contents of an array such that the last element of the array becomes the first element of the array and vice versa:

 Syntax

array.reverse() The JavaScript reverse method does not take any parameters and is used in combination with the array’s name. Let’s look at an example of the reverse method: let employeeNames = ['John', 'Jack', 'Chris', 'Hank']; console.log(employeeNames.reverse()); Note: This method modifies the original string.

 How to reverse array elements without changing the original array

As mentioned above, the reverse method modifies the original array. So if you want to reverse the array without modifying the original array you will have to use another method. Unfortunately JavaScript does not have a single specific method for this functionality, rather we have to use a combination of different methods to perform this function. The first method we will learn is using the spread operator along with the reverse method. First you will copy the array by using the spread operator and then call the reverse method on the newly created array: let employeeNames = ['John', 'Jack', 'Chris', 'Hank']; let reverseArr = [...employeeNames].reverse(); console.log(employeeNames); console.log(reverseArr); We can also use the push and unshift methods in combination with a for loop to reverse an array without modifying the original array: let employeeNames = ['John', 'Jack', 'Chris', 'Hank']; let reverseArr = [];for (let i = 0; i <= employeeNames.length - 1; i++) { reverseArr.unshift(employeeNames[i]);} console.log(reverseArr); In the example above, we started the loop from i = 0 as the array indexing starts at 0; then we set the condition as i <= employeeNames.length – 1 as the highest index in an array will always be one number less than the total number of elements in the array. Inside the for loop we used the unshift function to add the elements of the employeeNames array to the new reverseArr array. In the first iteration of the loop the i is equal to 0, so employeeNames[i] selects the first element of the array and the unshift function puts it on the first index of the reverseArr. On the second iteration i is equal to 1, so employeeNames[i] selects the second element of the array and the unshift function puts it on the first index. The element previously present on the first index now moves onto the second index. This process will keep on repeating until it reaches the last element and the whole array is reversed. We can also use the push method to reverse an array in the same way, but for that we will have to use a decrementing for loop index. let employeeNames = ['John', 'Jack', 'Chris', 'Hank']; let reverseArr = [];for (let i = employeeNames.length - 1; i >= 0; i--) { reverseArr.push(employeeNames[i]);} console.log(reverseArr);

 Conclusion

Reversing the elements of an array is one of those coding challenges which everyone should attempt when they are new to learning programming/scripting languages; It is often asked in coding quizzes and interviews. In this post we used the built-in reverse method to reverse a JavaScript array; this method modifies the original array, so we also learned other methods in which we could reverse an array while preserving the original array. For that purpose we learned to use the spread operator and push, unshift methods in combination with for loops.

How to Speed up the Execution of JavaScript Code

When developing an app or a website, one of the most crucial elements to consider is the app’s or website’s performance. As a user, I wouldn’t want any app to take a long time to load or whenever I click something and I have to wait for some action. Often if the webpage takes 5-6 seconds to load most users including me would leave the webpage. For web developers, JavaScript is a fantastic tool. Every web developer learned JavaScript at some point in their life. However, poor JavaScript code results in slower websites. With this in mind, a developer always looks at ways of improving his webpage. You are in luck because today we are going to talk about how to speed up the execution of JavaScript code.

 Activities reduction in Loops

A programmer often uses loops to shorten his code. However, it should be kept in mind that there are some bad ways of using loops that make your program slow. Let’s take a “for” loop example.

 Example:

for(let i=0; i < myArray.length; i++){ //Hello} This loop is programmatically right but its performance will be bad. We can put the myArray.length statement outside the loop so that it doesn’t have to calculate the length again and again until the loop ends.

 Solution:

let len=myArray.length;for(let i=0; i < len; i++){ //Hello} In this loop, we can see that the length is fixed and the loop doesn’t have to calculate the length of an array every time it iterates. Hence, speed increases and so does the performance.

 Dom Access Reduction

If we compare the JavaScript statement to accessing HTML Dom, we will find that accessing HTML Dom is very slow. This is not a problem if we are not accessing or performing many Dom operations. However, when you perform many dom operations it does affect the speed of the webpage. The solution for this is to store the Dom element in a local variable and then we can access that multiple times.

 For Example:

const myObj=document.getElementById("speed"),innerHTML="not achieved"; const myObj=document.getElementById("speed").hidden="false";//slow and hinders speed This makes our program execute inefficiently. Let’s look at another example that tackles this problem. const myObj=document.getElementById("speed"); myObj.innerHTML="achieved"; myObj.hidden="false"; Now that we have looked at Dom access reduction, let us shine the light on dom size reduction to improve the speed of our webpage.

 Dom Size Reduction

Before going into the dom size reduction, let us look at excessive dom size which means that your page has too many dom nodes/HTML components if the dom size is too large. It can also mean that your page dom elements are deeply nested. This results in the consumption of more power, hence reducing page performance or speed. The solution is that the number of elements should be minimized in the HTML Dom. The advantage of this is that it will improve the loading of the page as well as speeding the rendering process which is the displaying of the page. It is very handy especially on smaller devices like mobile phones etc.

 Eliminating Unnecessary Variables

This is the simplest trick to enhance your webpage performance. Why make variables when they are not needed? Also, why make variables where you know you are just using it for displaying it somewhere? When we avoid making unnecessary variables our web page performance increases.

 For Example bad code:

let firstName="Jhon";let lastName="Cena";let fullName=firstName+" "+lastName; alert(fullName); In this example, we can see that we are storing the firstName and the lastName in fullName just to display it in an alert. Wouldn’t it be better to directly alert the firstName and lastName? This is what eliminating unnecessary variables is.

 Solution (good code):

let firstName="Jhon";let lastName="Cena"; alert(firstName+" "+lastName);

 Delay Loading of JavaScript

To enhance your webpage performance, it is a common practice to put a script tag or within the script tag the JavaScript code at the end of the HTML page. The main purpose is that the browser should load the HTML first and then the JavaScript code. To put it in technical terms, while a script is downloading, the browser will not initiate any other downloads and all parsing and rendering will be blocked. We can also use “defer=”true”” in our script tag. The function of defer attribute is that it specifies that the script should only be executed once the page is finished parsing. In other words, it waits until the whole DOM is loaded. It should be noted, however, that it is only compatible with external scripts.

 Example:

<script> window.onload = function() { const ele = document.createElement("script"); ele.src = "code.js"; document.body.appendChild(ele); };</script>

 Avoid using the keyword “with”

With keyword is used to reference the properties or methods of an object as it is a kind of shorthand. Using the keyword “with” slows down speed. The other reason not to use the with keyword is that it clutters up scopes of JavaScript.

 Minify JavaScriptCode

Minifying or minimization of JavaScript code is another method of speeding up the execution of our JavaScript code. Minifying JavaScript code simply means removing or altering all the unwanted and unnecessary characters within JavaScript source code but without changing the functionality of the program. It includes multiple things like removing comments, semicolons as well as whitespaces. Apart from this it also involves the usage of short function and variable names. Let us see an example before and after minification of our code:

 Before Minifying:

//the function//which console log//the first message from personfunction firstMessage(name){ console.log("First Message is from: ",name);}//now call the function firstMessage("John");

 After Minifying:

function fMsg(n){console.log("First Message is from: ",n)}firstMessage("John");

 Conclusion

A developer always maintains the balance between the reliability and the optimization of the code. It is for this reason we discussed how to speed up the execution of JavaScript code in this article. All the tips and tricks mentioned above when used together will have a significant improvement on the speed of JavaScript code. However one should keep in mind that although performance is necessary it is not above detecting errors or adding functionalities.

How to Write a JavaScript Program to Get File Extension from File Name?

The file extension is a three or four-letter abbreviation or an acronym at the end of a file that tells you what kind of file it is under different operating systems. For example, the file name is code.js hence the extension here is js. The goal of this article is to show you how to write a JavaScript program to get file extensions from a file name. We will discuss two of the easiest and most used methods to find the file extension.

 Getting File Extension

 Method 1: Using split() and pop() Methods

We can use the combination of pop() and split() methods to get the file extension. The split() method returns a new array after splitting a text/string into an array of substrings and it will be separated by the character we passed to it in the method parameter. Let’s look at an example of a split method where we will initiate a variable with a file name and then split that on the “.” character: var filename = "code.js";var returned = filename.split("."); alert(returned); //code, js We can see in the above screenshot that the code and js are returned as separate separated by a comma. The pop() method removes/pops the last element of an array or string and returns that as a value. Let’s implement the pop() method: var filename = ["code" , "js"];var returned = filename.pop(); alert(returned); // js We can see in the below screenshot that the pop() method popped the last element of the filename array and returned it: Let us now combine the two i-e pop() method and split() method to achieve our task of getting the extension of a file: function getFileExtension(fileName){ //extract file extension const extension = fileName.split('.').pop(); return extension;}// passing the filenameconst fileExtension = getFileExtension('code.js'); alert(fileExtension); In the above code, we made a small function with the name of getFileExtension() so that we don’t have to repeat the process of writing the code again and again. The getFileExtension() function receives a filename parameter and then splits and pops the last element of the filename and returns the result.

 Method2: Using substring() and lastIndexOf() Methods

The substring() method is a built-in method of JavaScript that takes two arguments as parameters i-e start and end and extracts characters between those two positions or indices from a string and returns a substring from start till the end and not including the end. Let’s extract the rop from the word aeroplane: var machine = "Aeroplane";var extract = machine.substring(2, 5); alert(extract); // rop The lastIndexOf() method is used to find the location of a specified character or a substring in a string and returns an index value of the last occurrence of a specified value in a string. The lastIndexOf() returns a value of negative one (-1) if the value is not found. var machine = "Aeroplane";var lastIndex = machine.lastIndexOf("a"); alert(lastIndex); // 6 Let us now combine the two methods, substring() and lastIndexOf() to extract the file extension from a filename: function getFileExtension(fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1);}var filename = "code.js";var extension = getFileExtension(filename); alert(extension); // js The fileName.lastIndexOf(“.”)+1 returns the last position or index of the . In the file name and the +1 is because the index starts from 0.

 Conclusion

The file extension is the three or four letter abbreviation at the end of the file which identifies the file type. File extensions are important as it tells our computer what icon to use for a file and what software or application can open or edit that file. For example, the doc extension tells our computer that it is a Microsoft word file. Finding extensions is also crucial since there will be instances when we import files into our JavaScript and do actions based on the extension of that file. In this article, we explore the idea of how to write a JavaScript program to get file extensions from a file name.

How to Reverse a String

Reversing an array is a very popular coding problem that is often asked as an interview question to beginner JavaScript devs. Sometimes the interviewers add certain restrictions, forcing you to come up with ingenious solutions. In JavaScript, a string can be reversed by many different methods. In this post we will discuss the most creative and interesting methods for reversing a string.

 How to Reverse a String Using Built-In Functions?

A combination of different JavaScript built-in Array and String functions can be used to reverse a string. In the following example let’s use the .split(), .reverse() and the .join() methods to reverse the string. The .split() method will get the string as an argument and convert the whole string into an array, then the .reverse() method will reverse the whole array which will then be converted back into a string using the .join() method. let greetings = "Welcome to Linux Hint"; let convertedArray = greetings.split(""); // Converts the String into an Array let reversedArray = convertedArray.reverse(); // Reverses the Array let reversedString = reversedArray.join(""); // Converts the Reversed Array back into a String console.log(reversedString); We can also chain all of these methods together: let greetings = "Welcome to Linux Hint"; let reversedString = greetings.split("").reverse().join(""); console.log(reversedString);

 How to Reverse a String With a For Loop

A decrementing for loop can also be used for reversing a string. To reverse an array using a for loop, we first need to create a new empty string. We can then use the decrementing for loop to put each character of the string into the new string in the reverse order. var greetings = "Welcome to Linux Hint";var reversedString = "";for (let i = greetings.length-1; i >= 0; i--) { reversedString = reversedString + greetings[i];} console.log(reversedString);

 Conclusion

String Reversing is another one of those coding challenges which every coding beginner must attempt. It is a simple algorithm which is often asked in entry level technical or screening interviews. You can take several different approaches to solving this problem. In this post we learned to chain three built-in methods to reverse a string. Moreover we also learned to use a decrementing for loop to reverse a string.

How to Link JavaScript to HTML

JavaScript is a very popular scripting language which is used both on the client-side as well as on the server-side. JavaScript is necessary for our web pages as it makes our web page interactive. There are three basic requirements to become a front-end developer: HTML, CSS, JavaScript HTML is shortened for Hyper text markup language that provides structure to our webpage and CSS gives style to our pages. Finally, JavaScript as mentioned earlier makes our webpage interactive. JavaScript also helps in altering Html and CSS. Now a question arises that how can we link/connect JavaScript with HTML. Today in this article we will explore almost all the ways we can link JavaScript to HTML.

 What is a script tag?

Before going into the solution of how to link JavaScript to HTML, let’s look at the script tag. The <Script> tag is used to embed client-side scripts which are JavaScript. This tag has either scripting elements or references to another script file using the src attribute.

 Syntax

<script src="></script> This is a script tag with an src attribute in which we can provide a file name we want to reference.

 Using JavaScript within HTML file

We can link JavaScript to HTML by adding all the JavaScript code inside the HTML file. We achieve this using the script tag which was explained earlier. We can put the <script></script> tag either inside the head of the HTML or at the end of the body. It is totally up to us where we want to put it and when we want JavaScript to load. Programmers usually call the script tag whenever they want to generate content or apply some action. So by looking at the following code, it is a good practice to load javaScript after the HTML body. Let’s look at an example:

 Example

<body> <button onclick="myFunc()">Click Me</button> <script> function myFunc(){ alert("You Clicked me"); } </script></body> In this example, first, we created a button in HTML. We set an event to click. Whenever a user clicks on this button the myFunc() function will get activated. After that we put a <script> tag. All the JavaScript code went here. We put a function with the name of myFunc() where we showed an alert. Congratulations! We have successfully linked JavaScript with HTML by adding JavaScript code inside the script tag. This method is good for small web pages or one webpage. However, as your web app grows bigger the script code will also get bigger and it will become really difficult to handle as well as to read. The solution is to write JavaScript in a dedicated separate javaScript file and provide the reference of the JavaScript file in the HTML file.

 Using JavaScript in an external file

Using an external file for larger scripts is beneficial as we can divide our code into different JavaScript pages as well as in different files. It is achieved by referencing the JavaScript file name in the “src” attribute of the script tag in the HTML file. Let us change the previous example a little. The code will remain the same. We will make another JavaScript file by the name of “code.js”. We will put all JavaScript code in the “code.js” file and provide the “code.js” reference in the HTML file.

 For Example

<button onclick="myFunc()">Click Me</button><script src="code.js"></script> We referenced the “code.js” file using the src attribute of <script> tag. Now the code.js file: function myFunc(){ alert("You Clicked me");} The result will be the same as the previous example i-e.

 External JavaScript File Advantages

Let us formally state some of the advantages after discussing the external javaScript file: It separates our HTML code and JavaScript code JavaScript code becomes readable as well as maintainable. Another advantage is that cached JavaScript files act in speeding up page loading.

 JavaScript Selectors

In the previous examples, we took the help of an event. Suppose, we don’t want to add an event and we want to select an element from the html file. JavaScript helps us by providing different options for this which are called JavaScript Selectors. JavaScript Selectors main function is to select an HTML element and perform different actions on it according to our needs. JavaScript provides different options for this, one of them is the id. We can give an element an id attribute in Html and then access it. We access by: document.getElementById("idName"); Id is unique and used for only one element. JavaScript also gives us the option of selecting an element using a class attribute. We can use the class name for different elements. The Syntax is: document.querySelector(".className"); Another option JavaScript gives us is accessing JavaScript elements using tag names. Syntax for accessing tag names: document.getElementsByTagName("p");

 Example:

 HTML

<body> <button id="btn">Click Me</button> <script src="code.js"></script></body>

 JavaScript

const btn=document.getElementById("btn"); btn.addEventListener("click", function(){ alert("You clicked me");}) In this example we accessed the button element using getElementById(). After that we put an event that whenever a user clicks on the button an alert should be shown. We can achieve the same output if we use: const btn=document.querySelector("btn"); It should be kept in mind that we have to set the class attribute in the button element.

 Conclusion

Linking JS with HTML makes your website dynamic and interactive. In this post, we taught you how to link JavaScript to HTML. We discussed the two main ways of achieving this task. The first was using JavaScript within the HTML file. The second was using JavaScript outside the HTML file using a JavaScript file. To be a front-end developer it is necessary to work in both HTML and JavaScript and this article showed you how to link both these.

How to debug JavaScript in Chrome

In this article, we are going to explain how to debug JavaScript using DevTools in Chrome step by step. If you want to debug your JavaScript code in Chrome then you have to follow these steps as mentioned below.

 Project Overview

I am going to demonstrate an example of how to debug JavaScript Code within Chrome. In this step, I am going to give a basic description of the code. This project is about computing modulo operation between two numbers. This example permits you to pass the value of dividend and divisor respectively. Subsequently, on clicking the compute button, it will take a minute to calculate mod between two numbers and will give you the output. The syntax of modulo operation is as follows: x mod y = r Where x = dividend, y = divisor, and r = remainder There are two files in this project, .html and .js file. JavaScript file contains 5 functions in order to calculate mod of two numbers:
    Click handler: It gives an alert message if one or both input fields are empty Inputs are empty(): This function is used to check if input fields are empty or not updateLabel(): This function is used to compute the mod of two numbers getNumber1(): Used to get the value of first number getNumber2(): Used to get the value of second number
Javascript code is illustrated below: function onClick() { if (inputsAreEmpty()) { label.textContent = 'Alert: You have to enter numbers in both fields.'; return; } updateLabel();}function inputsAreEmpty() { if (getNum1() === '' || getNum2() === '') { return true; } else { return false; }}function updateLabel() { var value1 = getNum1(); var value2 = getNum2(); var mod = "value1" % "value2" label.textContent = value1 + ' % ' + value2 + ' = ' + mod;}function getNum1() { return inputs[0].value;}function getNum2() { return inputs[1].value;} HTML file code is illustrated below: <html> <head> <title>How to Debug JavaScript in Chrome Tutorial</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> h1 { font-size: 1em } input, button { min-width: 72px; min-height: 36px; border: 1px solid grey; } label, input, button { display: block; } input { margin-bottom: 1em; } </style> </head> <body> <h1>Calculate Mod between two Numbers</h1> <label for="number1">Enter the value of dividend</label> <input placeholder="Please enter number" id="number1"> <label for="number2">Enter the value of divisor</label> <input placeholder="Please enter number" id="number2"> <button>Compute mod(%)</button> <p></p> <script src="index.js"></script> </body></html> Output of the project:

 Bug Detection

The sad part is whenever we will run this code, it would show some bugs to you. As you can clearly observe in the example below, when we are inserting the values the output is undefined instead of an actual result. So, now we have to detect the original cause of the bug which is explained briefly in the same article later.

 Example

In this example, we are going to pass values that give the undefined output as shown in the picture below. So, now we have to fix this bug quickly. In this step, our main target is to detect the source of bugs. For rapid detection of the bug, you should debug the JavaScript code in Chrome. For this, you need to run the application on Chrome, and then you have to open devTool by pressing the short keys CTRL+SHIFT+I. After opening the devTool, you will be able to see the screen shown below. Besides many tasks performed by Devtool, it can also monitor requests, change CSS.

  Developers tool Overview

You can debug your JavaScript code in the source panel tab. It has 3 parts as shown below:
    File navigator page: Requests of every file can be listed in this tab. Code editor: It displays file contents Javascript debugging pane: Used to inspect JavaScript
Code Debugging The simplest way to debug a bug in your code is that you have to insert the console.log() function within your code for inspecting values simultaneously. function updateLabel() { var value1 = getNum1(); console.log('value1:', value1); var value2 = getNum2(); console.log('value2:', value2); var mod = parseInt(value1) % parseInt(value2); console.log('result:', mod); label.textContent = value1 + ' % ' + value2 + ' = ' + mod;} Although the console.log() function can be a good option for detecting the bugs but breakpoints could be a more effective option as it allows you to pause code during its execution and analyze the corresponding value. Moreover, a breakpoint is better than console.log() because working with console.log() you have to observe many steps which have to be done manually in order to view values in the console window while breakpoints make it easier by working directly.

 Insertion of breakpoints in code

In case you get back and have a look at the application’s functionality, you will get to know that the result of the modulo operation appears to be incorrect after clicking the “Compute button”. Therefore, you will need to put a breakpoint before the click event. Event listener breakpoints help you to find the specific event which you want to cease by expanding the corresponding group as shown below. As the picture clearly shows that by checking the click-box will stop the execution wherever the click listener event is present.

 Step into your code

The picture below illustrates that if you want to stop the execution of a specific line e.g. we say line 21, then we will click on it and observe a blue marker on that specific line which makes sure that the execution will automatically stop when it reaches line 21.

 Detecting the cause of a bug

As we put a breakpoint on line 21, which means that code always pauses whenever the execution of code reaches that line. When the code is paused on a certain line, then the scope panel specifies its local and global variables. As you see in the picture below, both values are not integers. They are enclosed in quotes as you see in the picture below as well as mod value also seems suspicious. Finally, the source of the bug is detected.

 Bug fixing

Now you can modify the code and test it again. Click on the resume icon as shown on the right of the window screen. Now replace line 20 with the line mentioned below and save the changes. var mod = parseInt(value1) % parseInt(value2); Then deactivate breakpoints and test the code with different values to check the correct outcomes.

 The output of 24%9 is as follows:

 The output of 5%3 is as follows:

 Conclusion

JavaScript is the most popular language and its need is increasing day by day. Almost everywhere JavaScript is being used. In this article, we explained debugging of JavaScript code in Chrome. Subsequently, we discussed each step in-depth. Example pictures are also provided for each step to help you understand.

How to create a dropdown menu with JavaScript

JavaScript adds dynamic behavior to your website, you can create various dropdown menus, navigation bars, animations, and handle how the page responds to each click. This makes the webpage interactive and adds “life” to a website. Many developers rely on Bootstrap for these purposes as it comes with built in components that can be reused easily and increase the productivity of a developer but understanding how each thing works on its own first is important before jumping into using reusable components. Here in this article we’ll discuss how to create a dropdown menu using JavaScript.

 Dropdown Menu with JavaScript

We all have seen dropdown menus and used them while filling various online forms for selecting a particular city, state or simply choosing from a bunch of dropdown options provided to us. These are toggleable menus that consist of multiple options from which the user can choose a particular option. These options can either be defined in the HTML list or as an array and they’re associated with a function. Whenever a user clicks on an option, the function is triggered and a corresponding action occurs.

 Important Points for Creating a Dropdown Menu

You can create a simple dropdown menu with the use of an HTML list that uses the <select> tag along with the <option> tag. An id is provided to the list which is used to get the option selected by the user. You can create a more complex dropdown menu using mainly JavaScript with a little bit of HTML. The options will be defined as an array. Let’s understand each of these better with the code for better understanding.

 Simple Dropdown Menu

First, create a list in HTML providing it some id in a form tag, here we provide it “option” as an id. Options are defined in each <option> tag and on change a function is called. The function is defined by the name “dropdownMenu()” which triggers whenever the option is selected. Last thing is an input is created with id “city” in which the option appears selected by the user. <html> <head> <title>Simple Dropdown Menu</title> </head> <script> function dropdownMenu() { var list = document.getElementById("option"); document.getElementById("city").value = list.options[list.selectedIndex].text; } </script> <body> <form> <b> Select your City from the list</b> <select id = "option" onchange = "dropdownMenu()" > <option> ---Choose City--- </option> <option> New York </option> <option> Amsterdam </option> <option> Paris </option> <option> London </option> </select> <p> Your selected city is: <input type = "text" id = "city" size = "20" </p> </form> </body> </html> Output:

 Dropdown Menu using div along with JavaScript

First, create two divs in the HTML tag that triggers the function and displays the menu on the screen. Define the list as an array and use documnet.createElement() method to create a dropdown list programmatically Then call the method appendChild() to append the dropdown menu at the end of the list. <html> <body> <div id="list"></div> <br> <div> <button id="show">Show the list</button> </div> </body> </html> <script> document.getElementById('show').onclick = function() { var items = ["New York", "Amsterdam", "Paris", "London"]; var select = document.createElement("select"); select.name = "city"; select.id = "city" for (const val of items) { var option = document.createElement("option"); option.value = val; option.text = val.charAt(0).toUpperCase() + val.slice(1); select.appendChild(option); } var label = document.createElement("label"); label.innerHTML = "Select your City from the list: " label.htmlFor = "city"; document.getElementById("list").appendChild(label).appendChild(select);} </script> Output:

 Conclusion

JavaScript is used for creating various interactive elements on the webpage to increase the dynamic behavior of the page. In this article we created a dropdown menu with the code. Firstly, a simple drop down menu was created using HTML and function being called through JavaScript, then we made it complex and created the dropdown menu with JavaScript and a lil bit of HTML. The items were defined as an array and a dropdown menu was created using built-in methods. Code is provided for both for your better understanding.

How to create an input box?

JavaScript is one of the world’s most famous programming languages which helps in creating dynamic and interactive web applications. Like any other dynamic language, it is a necessity to read, save, process, and output data from a user. When you need to handle user data without sending it back to the server, Javascript is extremely beneficial. JavaScript is significantly faster than sending everything to the server to be processed, but you must be able to receive user input and operate with it using the proper syntax. The focus of this tutorial will be on obtaining user input and displaying it on the screen using HTML elements or prompts.

 Method 1: Using Prompts

To connect with users, Javascript offers us a few window object methods of which one is the prompt() method. The basic function of the prompt() method is to display a dialog box and take input from a user. The prompt() method is most commonly used to store/save small amounts of information about the user and is most commonly used when the developer wants the user to input data before proceeding to the webpage.

 Syntax

prompt(text, default) The prompt() method takes two parameters: the first is the text parameter, which appears in the dialogue box, and the second is the default parameter, which is the default text displayed in the prompt’s input box. These options are both optional and can be left blank.

 prompt() Method Example

var name = prompt("Enter your name", "Enter name");if (name != null) { alert("Hello! "+ name)} In the above JavaScript code, we called the prompt() method and asked the user to input his name. The default value will be Enter name: Let’s remove the Enter name and type your name: Now when you click on the OK button you will see the Hello! Nas message alert:

 Method 2: HTML and JavaScript

Another method to create an input box is to use an HTML input box and then reference that and get its value. HTML: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <h3>Create Input Box</h3> <input type="text" id="myName" placeholder="Enter Name"> <button id="btn">Save</button> <script src="code.js"></script></body></html> In the above code, first, we defined an input box and then a button with the anime of Save. We then referenced the code.js file using the script tag. In the code.js file, all our javascript code will be present.

 JavaScript:

const btn= document.getElementById("btn"); btn.addEventListener('click', function(){ var name = document.getElementById("myName").value; alert("Name: "+ name);}); In the above code, we referenced the button with the id of btn from html and then added an event listener of click to it which will listen continuously and when someone clicks on the save button a function will run. In this function, first, we get the value of the input box using the id given to it which is myName. Then we alert this value.

 Conclusion

JavaScript is the programming language whose community is increasing day by day and rightly so as it is the programming language that makes our web page interactive. JavaScript offers us to interact with the users by taking input from the user and then saving that input or displaying that input. In this article, we took input from the user and displayed that input using two methods i-e prompt() method and referencing an input box from HTML.

How to call JavaScript function in HTML

JavaScript is emerging day by day and is used efficiently in web pages. Whenever JavaScript is called into an HTML page, it interacts dynamically on web pages. JavaScript makes web pages more intuitive and enhances user experience as compared to static pages. Calling functions of JavaScript into an HTML page is not a complex task. In this article, we demonstrate various ways of calling JavaScript functions in HTML.

 Inline JavaScript function

The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function. Now we are going to demonstrate a simple example. This example contains a simple HTML file in which we have defined a method functionName() within script tags in the head of the HTML as shown below. <html> <head> <script type = "text/javascript"> function functionName() { alert("You are learning how to call JavaScript function in html"); } </script> Furthermore, we created a button and associated the onclick() event with it as shown below. Subsequently, whenever the user clicks on the button the function gets invoked: <body> <h4>Hey, click on the button below to invoke the function</h4> <input type = "button" onclick = "functionName()" value = "Click Me"> </body>

 Example

<html> <head> <script type = "text/javascript"> function functionName() { alert("You are learning how to call JavaScript function in html"); } </script> </head> <body> <h4>Hey, click on the button below to invoke the function</h4> <input type = "button" onclick = "functionName()" value = "Click Me"> </body> </html>

 Output

 Call JavaScript function through external files

The second method is to call a JavaScript function in HTML through external .js files. External files of JavaScript are attached in the head section of the HTML file. First of all, you need to create two files i.e. .html file in which HTML code is written and the other is .js in which functions are defined. We have to create an HTML document once we are done with the creation of JavaScript. After incorporating the JavaScript file we have to either create a link or a button, then invoke the function defined in the JavaScript file.

 Example

This example contains a simple HTML file “articl.html” in which we link the external JavaScript file “jsarticle.js”.

 articl.html

<html> <head> <script type = "text/javascript" src="jsarticle.js"></script> </head> <body> <h4>Hey, click on the button below to invoke the function</h4> <input type = "button" onclick = "functionName()" value = "Click Me"> </body> </html>

 Jsarticle.js

function functionName() { document.write("You are learning how to call JavaScript function in html"); } Html and JavaScript files should be either saved in the same folder and if not then we have to provide a full path in the script tags present in the head section. In our provided example we have saved the HTML and JavaScript files in the same folder that is why we have provided the name of the JavaScript file instead of providing the full path. <head> <script type = "text/javascript" src="jsarticle.js"></script> </head> We have created a button in the body section and besides that button, we have also used the onclick event to call a function. Now, whenever the user clicks on that button the function will be invoked which is defined in the javascript file as shown in the below-mentioned picture. <body> <h4>Hey, click on the button below to invoke the function</h4> <input type = "button" onclick = "functionName()" value = "Click Me"> </body>

 Output

 Conclusion

In this article, we demonstrate how to call JavaScript functions within HTML. We have also discussed two methods. In the first method, we are including a JavaScript file within an HTML document. In the second method, we are calling JavaScript through external files. Both these methods have been briefly explained along with examples of how JavaScript functions can be invoked in HTML.

How to change CSS with JavaScript

The HTML language is simply a markup language that cannot perform any functions, and cannot execute codes based on various dynamic events. For this purpose, we’ve to use JavaScript to change the CSS style of any HTML element as HTML cannot do this on its own. There can be various reasons why we need to change CSS and manipulate with HTML elements, it could be to load the stylesheet dynamically, to change a button’s color when a user clicks it, or to write CSS. All of these changes can be done through JavaScript. In this article we’ll see various ways of accessing CSS with JavaScript and changing it.

 Using JavaScript to Change CSS

There are various methods which help in accessing HTML elements and through that we can manipulate the values of CSS. Some of these methods are explained below along with examples.

 Using getElementsByClassName()

The method getElementByClassName() takes in a string as a class name and searches the entire HTML document and returns the elements with the same class name. Once the class name is identified we can change the CSS properties as shown below in the example:

 HTML:

<html> <div class="col-md-12"> <div class="p-3"> <label>Input Box:</label><br> <input type="text" class="border_class" id="border" value="500"> <button class="ml-3" onclick="changeBorder()">Change Border</button> </div> </div></html>

 JavaScript:

<script> function changeBorder() { document.getElementsByClassName("border_class")[0].style.borderColor = "Green"; document.getElementsByClassName("ml-3")[0].style.backgroundColor = "Yellow";}</script> Here we searched the HTML element by classname and changed the CSS properties of those elements using style.backgroundColor and style.borderColor.

 Output:

 Using getElementById()

Another method to use is getElementById() which searches all the HTML elements with similar ids and performs the assigned function on them. Mostly various divs are used which are assigned with ids and these ids are searched using this method. This is the most used methods by developers, below is an example:

 HTML:

<html> <div class="col-md-12"> <div class="p-3" id="box1"> <label>Input Box:</label><br> <input type="text" class="border_class" id="border" value="500"> <button class="ml-3" id="btn" onclick="styleChange()">Change Border</button> </div> </div></html>

 JavaScript:

<script> function styleChange() { document.getElementById("border").style.backgroundColor = "Yellow"; document.getElementById("border").style.borderColor = "Red"; document.getElementById("btn").style.backgroundColor = "Green"; document.getElementById("btn").style.color = "White"; document.getElementById("btn").style.borderColor = "Yellow";}</script> Here we’ve used the method to search all the elements using their id and changed the CSS properties using style.

 Output:

 Using querySelector()

Another method that works just like the above two methods is the querySelector() method which can search by class name, id name and even by HTML tags but it only returns the first HTML element mentioned to search. Below is the ways to use the querySelector: document.querySelector("# id of div"); document.querySelector(". css class name "); document.querySelector("HTML tag like: div>"); Below is an example of querySelector() and how it can be used with class name, ids etc:

 HTML:

<html> <div class="col-md-12"> <div class="p-3" id="box1"> <label>Input Box:</label><br> <input type="text" class="border_class" id="border" value="500"> <button class="ml-3" id="btn" onclick="styleChange()">Change Border</button> </div> </div></html>

 JavaScript:

<script> function styleChange() { document.querySelector("#border").style.backgroundColor = "Yellow" document.querySelector(".ml-3").style.backgroundColor = "Green" }</script> Here we used the querySelector() method to search for classes and id of divs, and changed their CSS properties.

 Output:

 Conclusion

There are various reasons to change CSS, and the best way to do that is using JavaScript as it can easily access the elements of HTML and change their CSS properties. In this article we discussed how to change CSS using JavaScript, various methods provided to change the values of HTML elements. These make the job of developers easy and make the web page more dynamic. Through these methods we can change button colors on click, background colors, font colors etc easily and further manipulate with CSS properties.

How to add JavaScript to HTML

JavaScript is one of the scripting languages which is used to make interactive and modern web pages. Without any need of additional plugins, modern web browsers support JavaScript with built-in engines. Furthermore, while working with web files, JavaScript needs to be executed along with HTML. This can be done either by including inline JavaScript code within the <script> tag of the HTML file or you can add JavaScript through an external file. JavaScript tag <script> either used in the head section of HTML file or in the body section, it only depends where you want to load JavaScript. JavaScript can be written within <head> tags to keep out of the main content of HTML files. If you need JavaScript to execute across a web page layout then the script is usually called into the body section. JavaScript can be used in numerous ways in web pages like validation of the form, creating warning alerts, and much more. In this article, we will go through how to incorporate JavaScript into HTML files in depth. Following are the ways to incorporate JavaScript into HTML files.

 Embedding code

The <Script>…</script>tag is used to add JavaScript into web pages which helps to wrap JavaScript within the HTML programs. The code of Javascript can be either under the body section or head section depending on the structure of the application. Example1: JavaScript in head section <!DOCTYPE html><head> <title>page title</title><script> document.write("JavaScript added in head section");</script></head><body><p> This example shows how to include JavaScript in head section </p></body></html>

 Output:

Example2: JavaScript in the body section <!DOCTYPE html> <head> <title>page title</title> </head> <body> <script> document.write("JavaScript added in body section"); </script> <p> This example shows how to include JavaScript in the body section </p> </body> </html>

 Output:

 Inline code

When you need to call a function into HTML attributes then an inline code of JavaScript is used. JavaScript code can be used directly in various events like OnMouseover(), OnClick(), and many more. Main points should be kept in mind while using inline scripts: Useful for small scripts or scripts which only execute within one file. Difficult to read and understand if scripts are larger or used in several pages. Example1: This example shows how to incorporate JavaScript into HTML without tags. <!DOCTYPE html> <head> <title>page title</title> </head> <body> <p> <a href="#" onClick="alert('inline JavaScript!');">Inline Code </a> </p> <p> This example shows how to include inline JavaScript without script tags. </p> </body> </html>

 Output:

 Example2:

<!DOCTYPE html> <head> <title>page title</title> <script> let date = new Date(); alert("Today's date: " + date); </script> </head> <body> </body> </html> In the above example, whenever the user loads the web page the script displays an alert message showing the current date.

 Output:

 External file

JavaScript code can be written in a separate file with an extension of “.js” and then included in the HTML file. JavaScript file name can be included in the “src” attribute of the script. External files of JavaScript code can be reusable. Therefore, separate files for JavaScript code save you from rewriting the same software program. External files are much easier to manage.

 Example:

In this example, there are two files, index.html, and datescript.js. External file i.e. datescript.js included in the body section of the HTML file named as index.html. JavaScript named datescript.js is used to show the current date whenever the user loads the web page. Both .html and .js files are placed in the same folder.

 Index.html

<!DOCTYPE html> <head> <title>Date</title> </head> <body> <script src="datescript.js"></script> </body> </html>

 Datescript.js

let date = new Date(); document.body.innerHTML = "<h3>Date: " + date + "</h3>"

 Output:

  Conclusion

In this article, we demonstrate how to add JavaScript into HTML files. Subsequently, we discussed each method in-depth in order to incorporate JavaScript into your web pages. We discussed three ways for adding JavaScript into HTML files i.e. inline code, external files, and embedding code. Examples are also provided for each method to help you understand.

GET VS POST

While dealing with forms and data, there are HTTP methods that help in collecting and sending of data. These methods help between the interaction of server and client through the transfer of data. Such methods include two different request methods, GET and POST. HTTP protocol supports various methods that are involved for manipulation with data and are encoded before the data is sent, using the URL encoding scheme. The POST method supplies information from client to server in the message body whereas the GET method includes all the required data in the URL. After it’s encoded, the information is then transferred to the server. In this article we’ll discuss the difference between GET and POST and how they’re used, but before that let’s understand the concept of each individually.

 What is GET Method?

The GET method is used for fetching the data entered by the user but it has a drawback that it appends the input of the user into the URL, where the length of the URL is limited. The method is commonly used for submission of forms so that users can bookmark the result or for sending data that’s not secure. You can not send password or sensitive information through this method. Furthermore, you can not use this method for sending images or word documents that are in binary data form. To access the sent information the syntax $_GET is used which is an associative array.

 Example:

<!DOCTYPE HTML><?php if( $_GET["name"] || $_GET["city"] ) { echo "Welcome ". $_GET['name']. "<br />"; echo "Your city is: ". $_GET['city']. "."; } ?><html><body><form action="<?php $_PHP_SELF ?>" method="GET"> Name: <input type="text" name="name"><br> City: <input type="text" name="city"><br><input type="submit"></form></body></html>

 Output:

After submit the URL looks like this:

 What is POST Method?

The POST method appends the data of the form to the body of HTTP in a way that the data is not shown in the URL and there’s no limit on the size of the data that is to be sent. This method is mainly used for sending binary data and submitting secure information like password as the method goes through HTTP header, hence security depends on HTTP protocol. Hence, this method is more secure than the GET method and the data that is sent can be accessed through $_POST.

 Example:

<!DOCTYPE HTML> <?php if( $_GET["name"] || $_GET["password"] ) { echo "Welcome ". $_GET['name']. "<br />"; } ?> <html> <body> <form action="<?php $_PHP_SELF ?>" method="POST">Name: <input type="text" name="name"><br> Password: <input type="text" name="password"><br> <input type="submit"> </form> </body> </html>

 Output:

After submitting the URL looks like this:

 What’s the Difference between GET and POST?

As we explained the both methods separately, we saw that the GET methods parameters are displayed in the URL, whereas for POST methods the parameters were not present in the URL. This shows how secure the POST method is and while submitting important information, it’s always best to use the POST method instead of the GET method. Furthermore, the GET method is mostly used for fetching the data whereas, POST is used to manipulate the data that is stored in the server. The POST method can send unlimited data whereas for the GET method there’s a particular limit that is 2048 characters and it’s cacheable whereas POST is not cacheable.

 Conclusion

HTTP methods are used for dealing with data, sending and receiving data and manipulation. There are two particular methods used for HTTP requests: GET and POST, which differ from each other in various ways. In this article we discussed each method separately and then discussed how they differ from each other. Mostly to send secure data we use the POST method as it does not show the parameters passed in the URL, hence proving to be safer security-wise. We discussed further how one of them comes with a limit on data being sent. I hope now you’ve a better understanding of which method to use.

What is an anonymous function

Functions are blocks of code with reusable functionality mostly called with the name assigned to it to execute some lines of code. But, there are a particular type of functions without any identifier, called anonymous functions. Anonymous simply means without any identification, these anonymous functions or other programming languages are declared without any name or identifier. That’s the main difference between a normal function and anonymous function. In this article we’ll discuss anonymous functions, their syntax, how they’re declared and their usage along with examples for your better understanding.

 Anonymous Function

Most functions are declared with some identifier along with the “function” keyword that helps the user to call the function easily. But anonymous functions are declared only with the function keyword and no identifier, and it is not accessible after its creation and can only be accessed through a variable the function is stored in as a value. These anonymous functions can have multiple arguments but only one expression, following is the syntax of anonymous functions. Syntax: function(){ //Body of the function} As we can see that the function has no identifier, so it’s impossible to access it but, using a variable and storing the function in it as a value will help us accessing the function easily, as shown by the below example: var welcome = function () { console.log("Welcome to Our Website!");}; welcome(); Output: Here in this example, we simply used the function() keyword to declare a function and then stored it into a variable called “welcome”. Then through that variable we accessed the function.

 Usage of Anonymous Functions

Anonymous functions are easy to declare and are used for several purposes, some of which are listed below:

 Passing an anonymous function as an argument to other functions:

Anonymous functions can be used to pass as an argument to other functions. To understand the concept better look at the example provided below: setTimeout(function () { console.log('Execute after a second') }, 100); Here in the above example, we created an anonymous function and then passed that function to the setTimeout() function as its argument, and the function will execute the anonymous functions code after a second. This is one of the implementation and usage of anonymous function Output:

 Immediate Execution

Another reason to use anonymous functions is when you want the code within the function to be executed immediately and when no call is needed. Below is an example of immediately calling an anonymous function: (function() { console.log('Welcome to Our Website'); })(); Output: Here the function is immediately executed and it works as described below: First declare the function without any identifier as we do normally: (function() { console.log('Welcome to Our Website'); }) Now the function is declared but it won’t execute, so in order to execute it we use the trailing parenthesis “()” which are followed by the terminator “;” that’ll execute the below code: (function() { console.log('Welcome to Our Website'); })(); Sometimes we can also pass arguments into the anonymous function as shown below by the given example: let user = { firstName: 'Mark', lastName: 'Jacob'};(function () { console.log(`${user.firstName} ${user.lastName}`);})(user); Output:

 Arrow Functions with Anonymous functions

Arrow functions were introduced by ES6, which provide a short way of declaring anonymous functions, which reduces the lines of codes and make them more easily understandable as shown by the following example: These lines of code: let welcome = function () { console.log('Welcome to Our Website');}; welcome(); Can be converted to following lines of code using arrow function: let welcome = () =>'Welcome to Our Website'; welcome(); This will provide us with the below output, even though we’ve not returned anything but by default anonymous function returns. Output:

 Conclusion

Anonymous functions are those that are declared without any name or identifier, and to execute them we mostly use a variable to store them or parentheses along with the terminator “();” to execute them immediately. In this article, we discussed anonymous functions, their syntax, declaration and their usage. They help in immediate execution of code and used to pass as an argument in other functions. These functions are easily declared and can be used when we want immediate execution of our code.

What is JavaScript void (0)

At first, let’s start with the basic explanation of the word void. Void means “complete empty space”. So, when this term “void” is used in programming then it refers to return “nothing”. In simpler words, you can say that the void keyword is used to evaluate expressions and return an empty value. Void keywords are also used to obtain undefined primitive values. For <a> tag, JavaScript: void (0) could be presented as the value of the “href” attribute. JavaScript: Void (0) operator can be commonly used with hyperlinks. Now, let’s try to understand JavaScript void (0) operators by splitting them into two terms: JavaScript: It can be referred to as Pseudo URL. Whenever the browser gets the value through anchor tags, subsequently it starts to interpret the code followed by “:” instead of using the value as a path. Void (0): It evaluates expressions and returns an empty value.

 Why use JavaScript void (0) Operator

Operand 0 can be used in two ways: void (0) or void 0. Both of them work fine. 0 parameter passed in void function means it returns nothing. JavaScript: void (0) operator is used to prevent reloading or redirecting web pages. If someone wants to insert links on a web page without reloading then the JavaScript void (0) operator can be useful. In this case, void (0) on such links works best to prevent unwanted redirecting but allows specific functions like update value.

 When to use JavaScript void (0) Operator

In this example, the code will show an alert box whenever you click twice on the anchor tag. On the other hand, nothing happens if you click on the anchor tag once. JavaScript void (0) specifies that the onclick event is associated with the anchor tag to perform the required task. If you cannot use void(0) then whenever you click on the anchor tag it will show an alert box. <!DOCTYPE html><body><a href="javascript:void(0);" ondblclick="alert('hello')"> Click on Understanding JavaScript void(0)</a></body></html> OUTPUT The following example shows that code will show an alert box whenever you click on the anchor tag but the web page will not be reloaded. <html><body><a href="javascript:void(0); alert('Prevent reload and refresh')"> JavaScript:Void(0) Operator </a></body></html> OUTPUT

 Substitute of JavaScript Void (0)

Following are the few alternatives of JavaScript Void (0):

JavaScript void (0) function used in jQuery

You might face issues like it stops a web page from reloading when using JavaScript Void (0) in jQuery. You have to use the function i.e. event.preventDefault() to ignore the relevant issues.

 JavaScript: void (0) alternative: Use “#” in anchor tags

The alternative of JavaScript Void (0) is to use “#” in the anchor tag. Although, in most cases, it might redirect to a web page that you don’t want to load, else the page scrolls to the top or bottom. You must ensure that the click handler returns false.

 Conclusion

JavaScript void (0) function is used to prevent unwanted actions like reloading or redirecting web pages. In this article, we first explore what JavaScript void means then we studied further when to use this operator. The alternative of JavaScript void (0) is to use “#” in anchor tags and return false. Both of them work likewise. Some syntax errors might arise when using JavaScript void() and the return alert will scroll the page to the top.

How to convert a string to a number

Manipulating string is easy as it provides users with a bunch of built-in methods for changing the values, removing characters and changing the data type and converting them into numbers. Converting a given string into a number is useful and can be easily done through various JavaScript methods. This can be useful for developers so that they can manipulate values of string and perform calculations on these numbers easily. In this article we will discuss various methods provided by JavaScript to convert a string into a number, along with examples for better demonstration and understanding.

 Ways to Convert a String into a Number

Sometimes we want to perform various operations on some numbers and these can not be done when the data type of these numeric values is String. That’s why JavaScript provides users with built-in methods to convert Strings into numbers and make the task of performing operations and different operators on these numbers easier. Below are seven ways through which you can convert a provided string into a number, along with examples for your better understanding.

 Using Number()

One of the most common methods of converting a string to a number is by using the Number() method which takes in a string parameter and returns the number value. In case the provided string can not be converted to a number then the method returns Not a Number (NaN) value, below is an example: var example = "44.09"var example2 = "45.00003"var example3 = "46" console.log(Number(example));var a = Number(example2); console.log(a) console.log(Number(example3));//check typeOf console.log(typeof example2) console.log(typeof a) Output:

 Using parseInt()

Another method to use for converting a string to a number is by using parseInt() which takes in any numeric value as string and convert it into a number data type but if you pass a decimal number than it round off the number and returns an integer value as shown below through the following example: var example = "445.7"var example2 = "45.00003"var example3 = "66"var a = parseInt(example);var b = parseInt(example2);var c = parseInt(example3); console.log(a) console.log(b) console.log(c)//check typeOf console.log(typeof example) console.log(typeof a) Output:

 Using parseFloat()

Sometimes we want the decimal number to be returned exactly without any modification and for that we use the parseFloat() method. If you pass multiple numbers or a number with string then only the number is returned. But if you specify the string first and then a number, it’ll be unable for the method to convert it into a number and it’ll return NaN, as shown below through the example: var example = "445.767"var example2 = "45 50"var example3 = "66 years"var example4 = "year 1996"var a = parseFloat(example);var b = parseFloat(example2);var c = parseFloat(example3);var d = parseFloat(example4); console.log(a) console.log(b) console.log(c) console.log(d)//check typeOf console.log(typeof example3) console.log(typeof c) Output:

 Using Unary Operator (+)

Another way of converting a string into a number is by using the Unary Operator “+” along with the variable that will convert the string into a number as shown by the example given below: var example = "445.767"var example2 = "45"var a = +examplevar b = +example2 console.log(a) console.log(b)//check type console.log(typeof example) console.log(typeof a) Output:

 Using Math.floor()

This method takes in a string and return the number data type, but for decimals it returns the integer part only as a number, as shown by example provided below: var example = "445.7"var example2 = "45"var a = Math.floor(example)var b = Math.floor(example2) console.log(a) console.log(b)//check type console.log(typeof example) console.log(typeof a) Output:

 Using Double tilde (~~) Operator

Another way of simply converting a string into a number is by using double tilde “~~” along with the string which will convert any string into a number. In case of decimal values then it just simply takes the integer part and ignores the decimal part. var example = "60.67"var example2 = "33"var a = ~~examplevar b = ~~example2 console.log(a) console.log(b)//check type console.log(typeof example) console.log(typeof a) Output:

 Multiplication with a Number

Simplest way of converting a string into a number is by multiplying that string with 1, which will return a number. Both decimal and integer values will be returned with number as a data type shown through the below example: var example = "60.67"var example2 = "33"var a = example*1var b = example2*1 console.log(a) console.log(b)//check typeOf console.log(typeof example) console.log(typeof a) Output:

 Conclusion

There are various ways of converting a string into number, some built-in methods as well as some other operators to use for this purpose. In this article we discussed different built-in methods as well as some ways of converting a string into numbers. You can simply multiply the string by one which will convert it into a number or you can use built in methods as discussed in this article along with examples for your better understanding.

How to Call a Function

Functions are chunks of blocks that come with reusable functionality and reduce the complexity of the code. If an action needs to be done several times then functions are used to reduce the repetition of code in the program. These functions can be user defined or built-in that perform a specific action. Whenever we need the code within the function to execute we make a call and certain actions are performed. there are four ways through which you can call a function and perform the action. In this article we’ll discuss how to call a function and various ways to call it along with examples for better demonstration.

 Calling a Function

In JavaScript whenever we call a function, regardless of the way it’s called, two arguments “this” and the arguments parameters are passed to it which are implicit. “this” represents the condition or the context which will allow the function to execute whereas the arguments parameter consists of all the arguments that are being passed to the function. Following are the four ways in which functions are called along with examples for your better understanding.

 Calling a Function as “Function”

The most used and common way of calling any function in any programming language is calling it as a function itself. This can be done when you place some lines of code and execute those lines whenever a button is clicked then the function is called as a “function”. In the below mentioned example on the click of button the function is called directly and action is performed: <p>Click the button to say Hello</p> <button onclick="GreetingFunc()">Say Hello!!</button> <p id="div"></p> <script> function GreetingFunc() { document.getElementById("div").innerHTML = "Hello there?" } </script>

 Output:

 Calling a Function as Method

Another way to call a function is as a method and in this the function is defined as property on an object which is done by wrapping the function inside an object. In the example provided below the function “GreetingFunc()” is wrapped inside the object “hello” and we used the object dot syntax method to call the function whenever the button is clicked: <p>Click the button for greetings</p> <button onclick="hello.GreetingFunc()">Here for greetings?</button> <p id="div"></p> <script> hello = { GreetingFunc : function() { document.getElementById("div").innerHTML = "Hello Everyone" } } </script>

 Output:

 Calling a Function as Constructor

Constructors are used for initializing a state and setting it in an object or constructing an object. Calling a function as a constructor is a specialized way through which we send some inputs and receive a different output for each input. In the below example users enter their name in an input box and when they click the button the function “GreetingFunc()” is called and within that function the value of the input text box is obtained through the id assigned to the input text field. A new instance of the hello object is created by calling the function hello(). <input type="text" id="name"></input> <p>Click the button for greetings</p> <button onclick="GreetingFunc()">Here for greetings?</button> <p id="div"></p> <script> function hello(name) { this.name = name; } function GreetingFunc() { var name = document.getElementById('name').value; var greet = new hello(name); document.getElementById("div").innerHTML = "Hello "+ greet.name } </script> The keyword “new” shows that the function is being called as a constructor and the value is being saved in the variable greet which is later being used to print out the name on screen.

 Output:

 Calling a Function through call() and apply()

While working with JavaScript functions you’ve to keep in mind that the functions can have their own properties and methods and call() and apply() being the two of such methods. Both these methods allow the user to set the content in which they want to execute the function through “this” value. In the below example two people’s information is stored and is displayed when the value is passed inside the call() method. Here the fullName method is called to display the firstPerson name. <p id="div"></p> <script> const personFunc = { fullName: function() { return this.firstName + " " + this.lastName; }} const firstPerson = { firstName:"Max", lastName: "Andrew"} const secondPerson = { firstName:"Sam", lastName: "Andrew"} document.getElementById("div").innerHTML = personFunc.fullName.call(firstPerson); </script>

 Output:

The apply() method is used similarly to call a function but it accepts an array whereas the call() method accepts a list of values. const num = [2, 6, 11, 33, 4];const max = Math.max.apply(null, num); console.log(max);const min = Math.min.apply(null, num); console.log(min);

 Output:

 Conclusion

Functions consist of code that is being reused throughout with different inputs., functions can have their own properties and methods and can be called in four different ways. In this article we discussed how to call a function and discussed the four ways along with example and code. All these four ways are useful for any developer and while working with functions you should be aware about “this” keyword reference and its working.

How to install Node JS?

Node.js is a popular run-time JavaScript environment developed in 2009 by Ryan Dahl and is built on Google Chrome v8’s engine and was developed by Ryan Dahl in 2009. Node.js is free and open-source and runs on various platforms like macOS, Unix, and Windows. Node.js’ main purpose is to run JavaScript code outside of the browser. To build scalable and fast server-side and network applications by using JavaScript programming language, Node.js is used. Node Js is lightweight (easy to implement and minimalist syntax features), efficient, event-driven, and the best thing about Node js is that it is a non-blocking model. One of the reasons for Node.js popularity is because of the Node.js package manager i-e NPM. NPM or Node Package Manager is open source, free, and the largest Software library(containing over 800,000 code packages) in the world and is the default Package manager and installer for Node.js which is used for sharing software. As mentioned earlier, Node.js runs in various environments, and today in this article the question of how to install Node.js in windows 10 will be answered.

 Node Js Installation

Step 1: The first step in installation Node.js is to download the Node.js installer by going to the URL given below: https://nodejs.org/en/download/ Once you open the above URL in your browser, you will see the Node.js official page where you will see the Windows Installer button. Click on it. Keep in mind that the Node.js installer already has an NPM package manager. Once clicked your download will start. Step 2: Once completed go to the Downloads folder on your computer and open the Node.js file. Welcome to the Node.js Setup screen where you have to click on the Next button. Step 3: Next the License Agreement screen will be shown where you have to tick the accepting terms option and then click on the Next button: Step 4: This step involves choosing a destination folder where Node.js will be installed. Once you have chosen your destination folder, click on the Next button: Step 5: Now the custom setup screen will be shown where you can select components to include or remove from the installation which depends on your requirements. When you are done, click on the Next button: Step 6: The next window that will be shown is the Native Modules window where you can click on the automatic installation of all the required tools for Node.js or leave it unticked. Click on the Next button: Step 7: You can finally click on the Install button after which the installation will start: Step 8: Once the installation is completed you will see the completed Node.js Setup Wizard on the screen after which you have to click on the Finish button:

 Verify Installation

To verify the installation of Node.js, open command prompt (cmd) or Powershell in your Windows 10 and execute the below command: $ node -v Once you executed you will see the installed Node.js version: We can also check for the NPM version for which we have to execute the below command: $ npm -v

 Conclusion

Node.js, built on Google chrome’s v8 engine, serves as the server-side platform and was developed in 2009 by Ryan Dahl. Node.js 14.17.6 is the most recent stable version, and it comes with NPM by default. NPM or Node Package manager is the largest software library out there and is used for sharing software. Node.js uses JavaScript for developing applications. In this article, we taught you how to install Node.js on Windows 10 and then we verified it in the command prompt of Windows10.

How to run JavaScript in Visual Studio Code

Visual Studio Code (VSCode) has several built-in features like debugging, formatting, code navigation, and JavaScript IntelliSense. If someone wants to check whether a piece of code works or not then you might want to run JavaScript in VSCode. This article conveys the execution of JavaScript in VSCode. The steps to run JavaScript inside Visual Studio are as follows: 1.The first step is the installation of Node.js on your MacBook/Windows in order to call scripts through Node.js. You can easily download Node.js by visiting https://nodejs.org/en/ 2.In the second step you have to create a new folder then open this folder in Visual Studio Code. Subsequently, write JavaScript code and save it with an extension of “.js”. 3.Open up the operating system’s terminal inside Visual Studio Code by clicking on View on the topmost bar.

 Example

To run a script named index.js in Visual Studio Code then you should first make sure that node.js is installed. Open the terminal within Visual Studio Code. You can now easily run JavaScript in the terminal of VSCode by using node.js. The syntax of the node command used to run JavaScript code is shown in the VSCode terminal. $ node [filename].js In this example, we wrote the script to check if the number is even or odd. Subsequently, we execute the command in the terminal as shown below to get the output. In this case, we assigned 6 to the num variable and it gives the following output. // this script used to check if the number is even or oddconst num = 6;const result = (num % 2 != 0) ? "odd" : "even";// display the result console.log(`Number is ${result}.`);

 Output

On the other hand, we assigned 43 to the num variable and it gives the following output. // this script used to check if the number is even or oddconst num = 43;const result = (num % 2 != 0) ? "odd" : "even";// display the result console.log(`Number is ${result}.`);

 Output

 An alternative way to run JavaScript in VSCode using Code Runner Extension

This is the simplest method to run JavaScript. There are no configurations required in this method. You need to install Node.js either way on your machines as the code runner extension also needs Node.js. Following steps must be kept in mind to run JavaScript in VSCode using a code runner extension. 1.First of all, you need to install Code Runner Extension in order to run JavaScript code. This extension will consume a couple of minutes to install and it is really easy to install it. You can easily download the code runner extension by visiting https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner Then click on the Open URL:vscode button. The following window is shown as mentioned below. 2.After installation of the code runner extension, open JavaScript Code in VSCode. Press CTRL+ALT+N shortcut or you may press F1 then write Run Code to run the code. Subsequently, you will see the following output in the “OUTPUT” tab. // this script used to check if the number is even or oddconst num = 6;const result = (num % 2 != 0) ? "odd" : "even";// display the result console.log(`Number is ${result}.`);

 Output:

 Conclusion

Visual Studio gives quality, flexibility and also gives outstanding debugging experience to web applications using JavaScript. So, in order to run/execute JavaScript in Visual Studio Code we need NodeJS which acts as an interpreter. In this article, we demonstrate how to run JavaScript in Visual Studio Code and also explain an alternative way to run JavaScript in VSCode using Code Runner Extension along with detailed examples.

How to Remove Characters from Strings

JavaScript provides users with various methods and properties for string manipulation, to transform those strings or to search useful information from those strings. Sometimes we have various lines of code in which we need to make changes, search for a character or replace a character or remove a character from a string. All these tasks become difficult to do and hence methods are provided by JavaScript that makes the job easier. Users can easily use these methods to manipulate a string and transform it. In this article we’ll discuss how to remove characters from strings, various ways and methods provided by JavaScript along with examples for your better understanding.

 Remove Characters from Strings

JavaScript provides various in-built methods to remove characters from a string, some of which are listed below:

 Using substring() method

The method substring() takes in two parameters, the starting and the ending indexes and returns a substring as an output. You can also pass only one parameter, the starting index and it’ll split the string from that index mentioned till the end of the string, here below is the example: const example = "Welcome To the website!" console.log(example.substring(3)); console.log(example.substring(3,4)); console.log(example.substring(3,9));

 Output

 Using substr() method

Another method similar to substring() method is substr() that takes in two parameter starting and ending indexes and retrieves the characters between these specified indexes. Below is the example: const example = " Welcome To the website!" console.log(example.substr(2)); console.log(example.substr(1,3)); console.log(example.substr(1)); console.log(example.substr(2,example.length-1));

 Output

 Using replace() method

Another method is replace() method that takes in two parameters, the first one is the character to replace and the second one is the character to replace the character with. The output is a new string with the replaced values, below is an example: const example = "Welcome To the website!" console.log(example.replace("the", "our")); console.log(example.replace("W","w")); console.log(example.replace("e"," "));

 Output

 Using replace() method with Regular Expression

As we saw in the above replace() method example, when we wanted to remove the “e” character with whitespace, it only replaced the first occurring character. But what if we want to replace all the “e” characters or any character in the whole string with our desired character? Well, for that we use Regular expression which provide us with various modifiers such a s global modifies “/g” that searches the whole string and replace all the particular mentioned character in the entire string, below is an example: const example = "Welcome To the website!" console.log(example.replace("e"," ")); console.log(example.replace(/e/g," "));

 Output

 Using slice() method

The slice() method works in a similar way as substring() and the substr() method, it takes in two parameters where we define the starting index and ending index of the part which we want to slice from the string. The output is the sliced string, below is an example: const example = " Welcome To the website!" console.log(example.slice(5, 9)); console.log(example.slice(1, 2)); console.log(example.slice(1, example.length-1)); console.log(example.slice(2, example.length-1));

 Output:

 Using split() method

Another method JavaScript provides for removing characters is split() method which is used along with join() method. Firstly we use split() method to remove our desired character and it returns an array of strings. After that join() method is used to join the string, demonstrated below by an example: const example = " Welcome To the website!" console.log(example.split(" ").join("")); console.log(example.split("e").join(""));

 Output:

 Conclusion

Removing a specific character from a string can be difficult on your own sometimes, and hence methods are provided by JavaScript to manipulate string and remove characters from it. In this article we discussed various built-in methods for removing chcahters or part of a string from the whole string, along with examples. These methods are useful, and make the task of removing characters easy while dealing with lengthy codes.

How to remove white empty spaces from Strings

Manipulating string is a useful task while programming as it helps us in finding words, replacing words and especially for removing white spaces from string. JavaScript provides various built-in methods to users for manipulating with strings. Removing whitespaces from a string can be complex when it comes to tabs and line breaks and while you’re working with various lines of codes but JavaScript provides users with methods through which it becomes easier to manipulate strings and remove whitespaces from them and that’s why in this article we’ll discuss different methods and ways to remove whitespaces from a string, their explanation and how they’re used along with examples.

 Removing Whitespaces from a String

User can remove whitespaces from a string using different built-in methods, some of them are listed below: Regular expression split() with join() trim() Let’s understand each of these one by one, how they work along with examples for your better understanding.

 Regular Expression

In JavaScript the method “string.replaceAll()” or “string.replace()” accepts a regular expression to find matches with the provided string. Below is the example of a string where we used these methods to remove all the whitepsaces in the string and the g switch is used to search and replace the spaces from the entire string.

 Example:

const example = ' Welcome To Our Website '; console.log(example); //without using the method console.log(example.replace(/ /g,'')); //with the replace() method

 Output:

In order to remove all the whitespaces and not just the space character then you can use “\s” which will match against all the newline character, space character, tab character and translate it into a simpler code.

 Example:

const example = 'Welcome To Our Website '; console.log(example); console.log(example.replace(/\s/g,''));

 Output:

 spit() with join()

Another way to remove all the whitespaces from a string is splitting the string at a space character and then joining it back again. This can be done using the split() method along with the join() method as demonstrated through the below example.

 Example:

const example = 'Welcome To Our Website '; console.log(example.split(' ').join(''));

 Output:

You can also use \s for removing all the whitespace characters from the string.

 Example:

const example = 'Welcome To Our Website '; console.log(example.split(/\s+/).join(''));

 Output:

 trim()

Another method that JavaScript provides for removing all the whitespaces including space, tabs, no-break space and all the line terminator characters is trim(). This method can remove all the whitespaces from the provided string but if you only want to remove the whitespaces from the beginning or the end of the string then you can use trimStart() and trimEnd() methods to specify where to remove the whitespaces form.

 Example:

const example =' Welcome To Our Website '; console.log(example.trim());

 Output:

To remove whitespaces from only the beginning or end of the string we’ll use trimStart() and trimEnd() methods.

 Example:

const example =' Welcome To Our Website '; console.log(example.trimStart()); console.log(example.trimEnd());

 Output:

 Conclusion

Removing whitespaces can be a difficult task when you’ve hundreds of lines of code. That’s why JavaScript provides various methods for removing these whitespaces. In this article we discussed various ways of removing whitespaces from strings, some of these methods remove the overall space characters and with some method we can specify where we want the space to be removed. Examples along with code is provided for each method for your better understanding.

How to set, check and read a cookie value with JavaScript?

Cookies are small text files that keep a small bit of data on the user’s computer (around 4KB) and are used to store information about a user, for example, a user’s preferences for a website which the website can retrieve to personalize the web page when the user visits the site again. To put it simply, cookies help in a more convenient and personal website visit for the users. A cookie is sent to your computer by a website when you visit it and is saved in a file on your computer that’s accessible through your web browser. We will talk about how to set, check and read a cookie value with JavaScript in this article. However, before going any further let me stress on the point that cookies should not be used for storing critical/sensitive information like passwords or details of your credit card since malicious individuals could access them.

 Creating a Cookie

The document.cookie property creates, reads, and deletes cookies and this is the property, which represents all of the cookies connected with a document. To create a cookie first we should know that cookies are saved in name-value pairs for example: username = Obama; Let us now create a cookie: document.cookie = "username=Obama"; A cookie’s lifetime is set to the duration of the current browser session, which means it expires when the user closes the browser. To solve this problem we use the max-age attribute which ensures that the cookie persists beyond the current browser session. In the max-age attribute, we can specify the lifetime of a cookie in seconds i-e how long will the cookie remain before it is deleted. The life span of the cookie in the below code is 30 days: document.cookie = "username=Obama; max-age=" + 30*24*60*60; We can also use the expire attribute which takes the exact date rather than seconds in the GMT/UTC format and on that date the cookie expires: document.cookie = "username=Obama; expires=Thu, 26 Sept 2021 12:00:00 UTC"; Another attribute we can use in the creation of Cookie is the path attribute which tells the browser what path the cookie belongs to rather than the default path which is the current page. document.cookie = "username=Obama; expires=Thu, 26 Sept 2021 12:00:00 UTC; path=/"; We have to use the Javascript encodeURIComponent() as the cookie value contains commas, semicolons, and spaces and the encodeURIComponenet() ensures that the string doesn’t contain the commas, semicolons, and spaces as these are not allowed in cookies. document.cookie = "Username=" + encodeURIComponent("Obama");

 Reading cookie

We can read or get all the cookies of a current domain by using the document.cookie: var x=document.cookie; Just like in creating a cookie we used encodeURIComponent() in reading a cookie we have to use decodeURIComponenet() : document.cookie = "Username=" + decodeURIComponent("Obama");

 Deleting Cookie

We can also delete a cookie and, the process is very simple as we don’t have to specify some cookie value rather we can use the expire parameter and update it by using a past date for example: document.cookie = "username=Obama; expires=Thu,20 Nov 2018 12:00:00 UTC; path=/";

 Deleting Cookie

We can also delete a cookie and, the process is very simple as we don’t have to specify some cookie value rather we can use the expire parameter and update it by using a past date for example: document.cookie = "username=Obama; expires=Thu,20 Nov 2018 12:00:00 UTC; path=/";

 Cookie Example

Now that we know what a cookie is, how to create or read a cookie, let’s combine all that we have learned and create a cookie that stores a name whenever a user visits our website. We will take an input name from the user when the user enters our website for the first time and will store it in a cookie. When the user enters the website again he/she will get a welcome message on the website. To implement the above example, we will need 3 functions in which one of the functions will set a cookie, one will read/get a cookie value and the last function will check the cookie value.

 Set Cookie Function

function setCookie(username, value, expiry) { const date = new Date(); date.setTime(date.getTime() + (expiry * 24 * 60 * 60 * 1000)); var expires = "expires="+date.toUTCString(); document.cookie = username + "=" + value + ";" + expires + ";path=/";}

 Get Cookie Function

function getCookie(username) { let name = username + "="; let spli = document.cookie.split(';'); for(var j = 0; j < spli.length; j++) { let char = spli[j]; while (char.charAt(0) == ' ') { char = char.substring(1); } if (char.indexOf(name) == 0) { return char.substring(name.length, char.length); } } return "";} To obtain a single cookie we used the split method which will break down the name=value pairs and then search for the name we want.

 Check Cookie Function

function checkCookie() { var user = getCookie("username"); // checking whether user is null or not if (user != "") { //if user is not null then alert alert("Welcome again " + user); } //if user is null else { //take input from user user = prompt("Please enter your name:", ""); //set cookie if (user != "" && user != null) { setCookie("username", user, 365); } }} checkCookie(); The check cookie simply checks whether the name exists or not i-e whether the user has first visited our site or not. It checks by first calling the getCookie() method which checks whether the username exists or not and then if it exists displays the welcome message with the name of the user. If the username doesn’t exist then it calls the setCookie() method and the user then enters the name and the cookie is set. Below are the screenshots of when I first visited the site: Below is the screenshot showing the name I set after refreshing the page:

 Conclusion

A cookie is a small text file consisting of some information about a user and is a data packet that a computer receives and then sends back without altering or changing it. The browser cookies help in keeping track of user visits and user activities. For example, you have added some items to your cart and you are exploring the site and went to another page or you accidentally refresh it, without cookies your cart would become empty. We looked at how to set, check, and read cookies with examples in this post.

What is a method?

The simplest definition of a method is that it is a function that belongs to some class. However,, a method is a function that belongs to some object or a set of some instructions that performs a certain task. A function is a code of some instructions which performs a task. An object is a thing with certain properties and types. A shirt, for example, is an object, and its color or size are its properties.

 Method Invocation Syntax

myObj.myMethod('Argument'); Where myObj is an object on which the myMethod is called.

 What is a method?

A Javascript method is an action done on an object, and it is a property that holds a function definition, for example, suppose you have a function that has firstName, lastName, regno, and a method with the name of fullName that returns the first name and the last name of a person i-e the full name of a person. The fullName is the property and the function is the value. const student = { firstName: "Jhon", lastName: "Cena", Regno: 12311, fullName: function() { return this.firstName + " " + this.lastName; }}; alert(student.fullName()); The fullName() is the method of the student object and acts as a property. The fullName is executed like a function when invoked with () however it should be kept in mind that it is a property. We used this keyword in the above example because we wanted to access the property of an object within a method of the same object. Suppose we invoked the fullName without the parenthesis () then it will simply return the function definition: const student = { firstName: "Jhon", lastName: "Cena", Regno: 12311, fullName: function() { return this.firstName + " " + this.lastName; }}; alert(student.fullName);

 Method Addition to an Object

We can also add a new method to an object easily. We will change the above example code slightly to achieve our purpose i-e we will add a method to an object: const student = { firstName: "Jhon", lastName: "Cena", Regno: 12311,}; student.name = function() { return this.firstName + " " + this.lastName;}; alert("Student Full Name: " + student.name());

 Built-In JavaScript Methods

Built-in methods or functions are predefined pieces of code in a program or programming framework or a programming language that performs some specific task. This makes programming easy as programmers don’t have to create a new method or function and can simply directly use the built-in methods in their application. Like any other programming language, JavaScript also offers some Built-in methods for example: let name = "Jhon Cena"; alert(name.toUpperCase()); In the above example, we declared a name and then alert that name by using the inbuilt method toUpperCase() and we can see in the screenshot above that the name was converted to upper case. Apart from the toUpperCase(), there are also numerous built-in methods that we can use, for example:v Date() Date.now() Math.round(num) Math.floor(num) string.length() string.toLowerCase() Array.length array.push()

 Function and Method Difference

This topic is always a confusing one however we will today clear all your doubts by defining the key differences between a function and a method.
Function Method
The function is a set of code that performs some tasks.A method is also a function but it is associated with an object.
Can be called directly with the use of its name Can be called with the object name or method name
Can pass some data and after some operation can return the dataThe data is operated in a class
Data is explicit that is passed to a functionImplicitly passes the object which was called
Lives on its ownAssociated with an object property

 Conclusion

A method is simply a function that associates to a class, and that class belongs to an object. Methods are extremely useful as they can make a programmer’s life easy because methods are reusable, less coded, and can be easily implemented. In this short tutorial, we looked at what a method is and how it is implemented, as well as what JavaScript built-in methods are and the differences between a function and a method were discussed in the end.

What does JavaScript do / What can you do with JavaScript

Whenever we discuss web development we always talk about the importance of JavaScript, how it adds life to each web page and makes it more interactive. JavaScript is a scripting language that works on the client side of the web page to handle interactivity and increase dynamic behaviour by manipulating the content it receives from the server. JavaScript for a long time was used specifically for websites, to perform various actions such as validating a user’s information before logins, adding animated videos and images, performing specific actions on each click of a button, drop down menus and other interactive behaviors. But those days are no more and JavaScript is no longer just bound to handle web pages. It’s now widely being used in building mobile applications, web based games and networking applications. In this article we will discuss all the things JavaScript can do and is being used for and what you can do with JavaScript.

 Animate Websites

Did it ever happen to you that you opened a website and got amazed with all the elements popping around and how they react when you interact with them? Just like how this below mentioned website is using animation: This is all through JavaScript to keep the users engaged as well as make the website look more lively and aesthetically pleasing. Furthermore, a lot of time you open a site and the loading time takes a lot of time while you’re stuck looking at a white screen. To make the waiting process a lot less painful for users a lot of websites add loading animation to keep their users engaged such as the one provided below: Moreover, various scroll bars and navigation bar techniques are used to add animation to a website through JavaScript or how a button reacts on each click. In this way users can make their website more engaging and add various dynamic behaviours through the help of JavaScript.

 Web Applications

As technology is improving day by day, the ability to create various web applications is also increasing. Just like how Google Maps works, when you need to search a place you simply move your mouse on the map and the user can zoom in and the map shows us more details as the user keeps zooming in. This is all done through JavaScript.

 Server Applications

NodeJs is a runtime environment for JavaScript mostly used for backend APIs. After the introduction of NodeJs, JavaScript is no longer just restricted to browsers but now can also be used for server-side applications. Since then NodeJs is being widely used by many major companies like Twitter, WalMart and Uber to handle all their backends.

 Phone Applications

The times we’re living in; we’re surrounded by applications for mobile and there’s literally an application for everything out there. Whether you want to buy groceries, medicine or consult a doctor there is an application for each purpose. As the applications are increasing, the need for applications to be available on both the mobile operating systems (Android and iOS) is also increasing and building them for two separate platforms becomes costly. This is why there are various frameworks such as React Native by JavaScript that allows users to build a high standard application for various operating systems. This saves time and cost for developers and high quality applications have been built using the framework such as Facebook and Instagram.

 Smartwatch Applications

JavaScript frameworks are used in various types of applications and similarly a framework Pebbel.js was built by the company of watches, Pebble. It allows the developer to create applications for the company’s watches using JavaScript. This is though on a smaller scale but with the increasing popularity of JavaScript it’s obvious that other big names such as Apple or Google would be using such frameworks in their smart watches as well.

 Presentations

Long gone are the days when people used to use Powerpoint for making presentations. Now there is a library of JavaScript called RevealJS that allows users who are familiar with HTML and CSS to make interactive presentations. In case you are not from the programming world and not familiar with these two web technologies, then you have the option to use slide.com that uses the RevealJS library and creates slides for you.

 Games

Originally the games were being created using web browsers plug-ins but with time due to security concerns this concept became old and frowned upon and hence JavaScript came and allowed the developers to easily create various web based games such as the one below which is built around JavaScript.

 Flying Drones

We all are familiar with the craze of drones nowadays and how they’re used by every other filmmaker or Youtubers to add more versatility to their videos. Mostly drones are programmed using Python or C language but one Youtuber decided to program a drone using JavaScript. Although JavaScript isn’t a favourable language for this purpose, it still shows how versatile it can be and people can use it for various development purposes.

 Conclusion

JavaScript is a popular language and its need is increasing day by day. Nowadays almost everywhere it’s being used, specifically to build frameworks, libraries, backend of websites, games and mobile applications. In this article we discussed what JavaScript can do and where you can use it. There were days when developers used to use JavaScript to make their websites interactive and how their website interacts with each click, but now it’s not just restricted to that purpose. JavaScript is versatile and you can use it for various development purposes only if you have mastered the language.

What does a modulus operator do?

JavaScript is one of the most widely used dynamic and scripting programming languages for creating web pages and applications and like any other programming language, JavaScript offers operators which are specific symbols to perform operations on the operand. For example: 3-2; //1 In the above example, 2 and 3 are operands, and “-” is an operator. JavaScript offers a bunch of operator types in which one of them is the Arithmetic Operator that is used to perform an arithmetic operation, for example: var add = 3+2; //5 In the above example, the operator + is used to add the two numbers 3 and 2. The arithmetic operators include +, -, *, /, %, ++, –, and **.

 What is Modulus Operator?

The modulus operator is also called modulo operator and remainder operator and it returns the remainder of a division sum when the first operand is divided by the second operand, the remainder is returned. Syntax: A % B It is read as A mod B and A and B are operands. Example: var num1=9;var num2=2;var num3=3; alert(num1%num2 +", "+ num1%num3 ); //1,0 In the above example, we initiated three numbers and then checked the mod with num1 and num2 and num1 and num3. The output of the above code is:

 Finding Even and Odd number

The modulus operator is very useful in finding whether a number is even or odd. For example, an integer is even if it is divisible by 2 and remainder is zero and an integer is odd when the remainder is not zero. So, we can use the modulus operator and find whether an integer is even by finding the remainder. If integer%2 === 0 then the number is even and if the integer%2 ===1 then the integer is odd. Let’s implement the above theory: function checkEven(num) { return num % 2 === 0;}function checkOdd(num) { return num % 2 === 1;} console.log(checkEven(4)); // true console.log(checkEven(8.6)); // false console.log(checkEven(7)); // false console.log(checkOdd(5)); // true console.log(checkOdd(8.6)); // false console.log(checkOdd(8)); // false

 Finding Fractional part of a number

Let’s look at another problem where we are asked to find the fractional part of the number i-e the number after the decimal point for example if you have a number 3.5, we have to extract the 0.5 and return it. We can use the modulus operator to get our desired result in the following manner: function getFractional(num) { return num % 1;} console.log(getFractional(3.5)); // 0.5

 Conclusion

After dividing two numbers, the function of the modulus or modulo operator is to calculate the remainder. In this article, we saw what modulus operator are and what modulus operator does along with examples. We’re confident that after reading this tutorial, you’ll be ready to use the Javascript modulus operator like a pro.

Type conversion

In everyday life we use the term conversion. Whether we want to convert a currency into another or a file of one type to another. In programming, conversion plays an essential role which changes the dynamic of our program. Sometimes we want to convert a variable that’s compatible with the variable of different types and hence, this type of conversion of one type of data to another is called Type Conversion. These conversions can involve: Number to String conversion or vice versa Number to Boolean conversion or vice versa Number to Date conversion or vice versa In this article, we will learn different type conversions along with examples for better understanding.

 Type Conversions

JavaScript deals with type conversions in two ways: Implicit Type Conversion (conversion done automatically by JavaScript) Explicit Type Conversion (conversion done through the use of JavaScript methods) Let’s understand these separately along with examples.

 Implicit Type Conversion

We all are aware that JavaScript is a language that is loosely typed and due to this, it converts some data types into another automatically. This is called Implicit type conversion. It happens when you apply different types of operators to your values. Following are some examples for your better understanding:

 Converting to String:

Below is an example of converting the given data types to string. // numeric string used with + results in string let con; con = '2' + 2; console.log(con) // "22" con = '55' + false; console.log(con); // "55false" con = '5' + null; console.log(con); // "5null" con = 'hello' + 'world'; console.log(con); // “helloworld”// non-numeric string used with - , / , * results to NaN con = '455' - 'hello'; console.log(con); // NaN Here, numeric and non-numeric strings are used. Numeric string added with number simply returns the string of them combined. Whereas, subtracting two non-numeric strings returns NaN (Not a number). Output:

 Converting to Number

Below is an example of converting the given data types to numbers. // numeric type of string with -, /, * gives a number as an output let con; con = '22' - '2'; console.log(con) // 20 con = '22' - 2; console.log(con); // 20 con = '25' / 5; console.log(con); // 5 Output:

 Converting Boolean to a Number

Below is an example of converting the boolean data type to a number. // boolean has 1 as true and 0 as false let con; con = '5' - true; console.log(con) // 4 con = '22' - false; console.log(con); // 22 con = 25 + true ; console.log(con); // 26 For boolean, it simply adds the value of true and false to the number and returns a numeric value. For true the value is 1, and 0 incase of false. Output:

 Converting Null to a Number:

Below is an example of converting the null data type to a number. // null has 0 value when used with a number let con; con = '5' - null; console.log(con) // 5 con = 5 + null; console.log(con); // 5 con = 25 + null ; console.log(con); // 25 As the null holds 0 as value, so it had no impact whether it was added or subtracted. Output:

 Explicit Type Conversion

To make the job of converting one data type to another, JavaScript provides us with various built-in methods. These methods convert strings into numbers or boolean or vice versa. This type of using of methods for conversions is called Explicit type conversion. Following are some examples for your better understanding:

 Converting to String

To convert your data type into string, JavaScript provides built-in methods string() and toString(). Example: // String() let con; con = String(543); console.log(con) // "543" con = String(null); console.log(con); // "null" con = String(undefined) ; console.log(con); // "undefined" con = String(true) ; console.log(con); // "true" //toString con = false.toString() ; console.log(con); // "false" Output: Here, note that when null and undefined is used with the String() method it converts them to string. Whereas, the toString() method generates an error.

 Converting to a Number

Number() method is there to convert numeric string values and boolean values to Number data type. Example: // String to Number let con; con = Number('543'); console.log(con) // 543 con = Number("3.26e1"); console.log(con); // 32.6// boolean to Number con = Number(false) ; console.log(con); // 0 con = Number(true) ; console.log(con); // 1 // null, undefined con = Number(null) ; console.log(con); // 0 con = Number(undefined) ; console.log(con); // NaN Here note that when null is passed, it generates 0 whereas for undefined it gives NaN (Not a Number) as an output. Output:

 Converting to Boolean:

Similarly, for converting into a boolean expression method is available called Boolean(). Example: // 0, null, undefined , NaN generates false let con; con = Boolean(''); console.log(con) con = Boolean(null); console.log(con); con = Boolean(0) ; console.log(con); con = Boolean(NaN) ; console.log(con); // anything that contains any value generates true con = Boolean("hello") ; console.log(con); con = Boolean(" ") ; console.log(con); con = Boolean("13333") ; console.log(con); Output: Here, anything with some value will generate true. Whereas, anything not defined or without a value generates false.

 Conclusion:

Type conversion is a useful way of converting various data types into other data types as sometimes we want to perform some actions on a variable but it’s not possible due to its data type. In this article, we discussed why type conversion is necessary and various types of conversions. JavaScript provides us with two types of type conversions. There are some built-in methods provided by JavaScript to make type conversion easier. These methods provide the user the shortest way to convert their values and make them compatible in different data types. Through this you can make your program cleaner and readable.

What are arrow functions

One of the best features that modern JavaScript has provided us is the arrow function denoted through “=>”. Also known as “fat arrow” comes with various benefits in programming. It comes with “this” binding and using these makes the code look more organized and shorter. These functions are the reason why arrow functions are strictly preferred over other types of function declaration. But with these perks also comes some drawbacks as well. In this article we’ll learn how to write functions using arrow functions, and how to convert your simple functions to arrow functions. But before jumping into that, let’s understand some basic concepts about arrow functions.

 Arrow Functions

ES6 provided us with one of the most important and useful features that is an Arrow Function which helps in declaration of functions in a simpler way and reduces the lines of code. The syntax of arrow function is mentioned below: Syntax: let functionName= (p1, p2, ...pN) => { statement(s)} Here, functionName: The name of the function p1, p2,…. pN: These are the parameters of the functions statement(s): The lines of javascript code inside the body of the function. Using these we can convert our complex code into a more precise and compact version. Following are some of the features it provides:

 Implicit Return

Through this the use of any kind of parentheses, functions or the return keywords become optional, allowing the implicit return. Here’s an example: //arrow function example.onclick = (x, y, z) => this.doSomething() //equivalent to simple function example.onclick = function(x, y, z) { return this.doSomething();}.bind(this); Through the use of arrow functions, it’s simply allowing only a single expression and returning it implicitly. “this” binding : It automatically binds the keyword “this” to the code surrounded by arrow functions. For example: var x = this; example.onclick = function() { x.doSomething();}; to example.onclick = () => this.doSomething() Moreover, It provides a shorter, simpler and more compact version of your code.

 How To Use Arrow Functions

In JavaScript, we can use arrow functions with single, multiple or even no parameters. They’re useful for one line action, shrinking multiple line code into fewer lines and hence saving space. Let’s understand this with example:

 JavaScript Arrow Function with no Parameters

Following syntax is used when the arrow function works with zero parameters. Syntax: () => { statement(s) } Here, the statement is the body of the function containing lines of code. Example: let print = () => console.log("hello"); print(); In the above example, we’re simply printing “hello” using the arrow function. As you can see, the arrow functions do not have any name so they are also known as anonymous functions. Ultimately, we can not call or reuse them again when needed as they do not have any name but if we have to call or reuse the arrow functions, we need to assign them to a variable and then call them using that variable name. Here, we’ve assigned it to the variable “print” and called the variable in the second line. Output:

 JavaScript Arrow Function with single Parameter

In case of a single parameter, following syntax is used: Syntax: (p) => { statement(s) } Or, you can remove the parentheses and rewrite it like: p => { statement(s) } Here, the statement is the body of the function containing lines of code and p is the parameter passed. Example: In this example arrow function is being used as an argument of the map() method that converts a string array into an array containing string’s length: let days = ['Monday', 'Tuesday', 'Wednesday']; let lengths = days.map(days => days.length); console.log(lengths); Output:

 JavaScript Arrow Function with multiple Parameters

Following syntax is used when passing two or more parameters: Syntax: (p1, p2, ..., pn) => statement; Here, the statement is the body of the function containing lines of code and p is the parameter passed. In this the “=> statement” is equivalent to: => { return statement; } In the below example a sort() method is used without using arrow function, to sort numbers in descending order: let num = [3,1,5]; num.sort(function(a,b){ return b - a; }); console.log(num); This can be transformed into an arrow function let num = [3,1,5]; num.sort((a,b) => b - a); console.log(num); In the above example, the function has a single expression “b-a” so it simply returns the result of the expression. But in case of block syntax, you have to mention the return keyword. Output: In this way, we can transform any function into an arrow function. But, there are two points that need to be kept in mind while working with arrow functions: Arrow function should not be used for the creation of methods inside objects Arrow functions cannot be used as a constructor.

 Conclusion

Arrow functions are the easiest way to declare any functions and it reduces the lines of codes, without affecting the functionality of the code. In this article we learned that arrow functions are extremely useful, how they convert a complex syntax and lengthy line of code into more compact and simpler code. Moreover, it’s not necessary to name an arrow function unless you’ve to call or reuse the function. At first, arrow functions might seem difficult but with time as you understand the concept, they become easier and convenient to implement. Hence, converting your code to fewer lines with simpler logic.

Top 5 JavaScript Frameworks

There was a time when JavaScript was just a client-side language, but now it’s considered as a web language, as it is not only being used for building server-side applications but also for building various mobile applications and web based games. This is not it, JavaScript has various frameworks which come with pre-written code and functionalities that can be reused. These frameworks help users to minimize the workload of writing a code on their own and hence it makes the job easier. The demand for JavaScript is increasing everyday and its frameworks are being used by various large companies. These frameworks increase the developers productivity as they already provide pre written codes and functionality, so developers can expand those. That’s the reason why mostly developers prefer frameworks and many companies create their own frameworks according to their needs. Here in this article we’ll discuss top 5 JavaScript Frameworks that are being used everywhere.

 React.js

The most popularly known framework that is being used by various big companies is React which was built by Facebook. The company originally built this because Facebook Ads were increasing and growing faster everyday, and the job of handling them was becoming extremely difficult. To simplify their works, they built a library to make their work easier but later they released it to the public and made it open-source. React contains reusable components and each of these components represent a specific portion of the webpage, such as logo, an input box and a button. React can be easily learned if you’re already good at JavaScript as it uses a syntax that combines both JavaScript and HTML called JSX. Sometimes developers might feel difficulty understanding and working with JSX but with time developers realise how beneficial it’s as React is being used by large companies and if you’re into front-end web development you should definitely learn React.

 Angular

Another one of the popular and highly used frameworks is Angular that is being operated by Google and designed for developing Single Page Application (SPA). Many popular websites such as Youtube, Google use Angular as it provides the developer with the best features to combine JavaScript with HTML and CSS. Angular also has a similar component structure like React, which can be reused and manipulated easily. TypeScript is needed for writing applications to Angular, which is a superset of JavaScript that supports static typing and classes and you can access hybrid types, modifiers and more in TypeScript. Angular is a reliable framework due to its support from Google as well as it being the first choice for many Google app developers and if you’re new then it’s definitely a fantastic framework to learn.

 Vue.js

Vue is another popular open-source framework of JavaScript that is being used for creating various creative user interfaces and it is designed to be adaptable. Many large companies like Stackoverflow and Playstation along with thousands of other websites are using Vue for their UI. Vue is easy to learn if you’re already good at HTML and JavaScript. It comes with a command line interface which speeds up the development as it offers various instant prototyping and plugins. Other features of Vue are components, two way data binding, and templates. Reactivity focus is another feature of Vue which occurs due to update and change of any JavaScript objects in Vue. Furthermore, it uses Shadow DOM which makes the rendering of the page faster and Vue is simpler when it comes to API and design so the developer can build simpler applications in a day.

 Node.js

One of the most popular server side platforms which was built on Google Chrome JavaScript Engine is Node.js. For running JavaScript code and building server side applications, it provides a runtime environment. Many big companies use Node.js as it’s lightweight and efficient due to its features such as asynchronous, non-blocking I/O model and single threaded. Application builds using Node.js are written and are run within the runtime environment of Node.js. One Of the key features is that it’s good for editing the applications and making changes as another user can access and edit the document live as we do in Google Docs. It comes with the largest ecosystem of open source libraries such as npm and it’s being used by companies like Uber, Paypal and Walmart.

 Ember.js

Another popular open-source framework is Ember.js that was released originally by Yehuda Katz, and many other companies support the framework which uses Ember.js such as LinkedIn and Yahoo. Many large companies use it such as Apple Music was built using Ember as the framework is highly scalable and is suitable for larger scale projects. Ember comes with various built in tools which are easier to get started with and even for working with backend data, it provides data and is highly flexible and convention over configuration is preferred by it. This framework has been in the market for over 10 years and is getting better day by day, and definitely the best one to learn.

 Conclusion

JavaScript provides users with various frameworks that help the developer to do their job easily and more effectively, increasing their productivity. In this article we discuss the top 5 best frameworks provided by JavaScript which are popular and are being used by large companies and thousands of websites. They make building of applications easier for the developers and developers can extend the pre written code according to the demands of the website.

What is the “this” Keyword?

If you have programmed in Java, C++, or any other language you must be familiar with the “this” keyword. However,, it works a little differently. It is different because JavaScript offers a strict mode. Strict mode is where we cannot use undeclared variables. Strict mode also helps in debugging. The keyword “this” is widely used in almost every programming language. However, it is also the most confusing concept. If you are a beginner don’t worry, today we will cover almost everything about the “this” keyword along with examples. So sit tight, and let the ride begin.

 What is “this” keyword

The simplest definition of the “this” keyword is that it points to or refers to an object to which it belongs. We can also say that it references that object which is calling the function/method currently. Now that we know what the “this” keyword means, let us discover where it is used. The value of the “this” keyword also differs based on where it is used.

 Using “this” keyword alone

The keyword “this” can be used alone without any method. However, it then holds the reference to the global object. For Example: const xyz=this; alert(xyz); In this example, we initialized a variable, which stores the reference to the global object. It should be kept in mind that the browser window global object is [object window]. When we run the following code, we will get the following alert: We can also use the “this” keyword alone using strict mode. The solution will be the same i-e it will show the [object Window] alert. The code will look like this: const xyz=this; alert(xyz);

 Using “this” keyword in Function

Using the “this” keyword in a function is the default way. “this” keyword will also refer to the global object in a function. For Example: function myFunc(){ alert(this);} myFunc(); However, if we use this keyword in strict mode then the result is undefined. It is because in strict mode JavaScript restricts default binding. For Example: use strict"; function myFunc(){ alert(this); } myFunc(); In this example, we used “use strict”. We will be returned undefined when we run this code.

 Using “this” keyword in Event handlers

Event handlers handle events. For example, if you click a button, that click will be handled by event handlers. If we want to refer to that button element in HTML from which we received the click then we use the “this” keyword. For example, suppose we have a button. We want to make it vanish once we click it. We will achieve it by the following code: Html: <body> <button class="vanish-btn">Click me to see magic</button> <script src="code.js"></script></body> JavaScript: const btn= document.querySelector(".vanish-btn"); btn.addEventListener('click',function(){ this.style.display="none";}) In this code, in HTML we first created a button with the class name of “vanish-btn”. After that, we put the script tag where we referenced the file name of JavaScript. In the JavaScript file, we first get the reference of the button in “btn” with the help of the class name. After that, we put an event listener with the click of a button. In this whenever the button will be clicked, the callback function will run where we made the display of the button none. Before clicking the button the browser will look like this: When we click on the click me to see magic button it will vanish.

 Object Method Binding

We will give some examples first and then we will discuss it to grasp the concept. However, keep in mind that the keyword “this” is the player object defined in the following example or the parent object which it is referencing. const player = { name : "Hazard", club : "Chelsea", shirtNo : 10, myFunc : function() { return this.name; }}; alert(player.myFunc()+ " plays for " + player.club); In this example we initiated an object with the name of “player”. We specified its properties like name, club, and shirt number. After that, we made a function. In the end, we alert the player object function and the club he plays for. This is used in the myFunc() function. In this, it is referencing the player name with the keywords “this. name”. The result within an alert will look like this:

 Keyword “this” in an arrow function

Arrow functions were first introduced in the ES6 version and have a similar function to a standard JavaScript function except that arrow functions shorten the syntax. For example: function myFunc(){ return "Champions of Europe"} myFunc(); This can be written as: const myFunc= ()=>{ return "Champions of Europe";} Keyword “this” is handled differently in an arrow function than in the default function. To be precise, arrow functions have no binding of the “this” keyword. Also, the “this” keyword refers to the variable or object that defined the arrow function. For Example: const player =()=> ({ name : "Hazard", club : "Chelsea", shirtNo : 10, myFunc : function() { return this.name; }}); alert(player().myFunc()); Keyword “this” here referenced the player as the player-defined the arrow function.

 Conclusion

In this article, we discussed what “this” keyword is and how it is used. We also discussed where and how we can use the “this” keyword. All this with the help of examples. “This” keyword is an important concept of JavaScript and mainly beginners struggle with this. We hope that this post has clarified any ambiguities you may have had.

String search Methods

During programming, the user needs to search for specific values in a string. These values could be a substring or position of a specific word in the string. For this, JavaScript has various methods that can be used while searching a string.

 String Search Methods

JavaScript provides various string searching methods, each with their own unique functionalities. Each method serves a different purpose, whereas some might also have different parameters. These methods are: search() replace() indexOf() lastIndexOf() Let’s understand each of these one by one.

 search()

This is an in-built method that allows users to search for a specific word in a string. As a result, it returns the position of that word. Syntax: string.search(valueToSearch) Here, valueToSearch represents the expression that needs to be searched. Return Value: A number is returned which shows the index of the value that is searched in the String and in case of no result, -1 is returned. Here’s an example for better understanding: <html><body><p>Hello!! Welcome to our Website..</p><p>What's the position of "to"? Click the button to see the position.</p> <button onclick="searchMethod()">Search</button> <p></p> <script> function searchMethod() { var str = "Hello!! Welcome to our Website.."; var n = str.search("to"); document.getElementById("div").innerHTML = n; } </script> </body> </html> In this the search method searches for the word “to” and returns the position of it. Output: Well, what happens when the search method is unable to find the specific word in the string. Following example demonstrate this: <html><body><p>Hello!! Welcome to our Website..</p><p>What's the position of "here" in the above string? Click the button to see the position.</p> <button onclick="searchMethod()">Search</button> <p></p> <script> function searchMethod() { var str = "Hello!! Welcome to our Website.."; var n = str.search("here"); document.getElementById("div").innerHTML = n; } </script> </body> </html> In this example, the word “here” is not present in the string. That’s why it returned -1 as an output. Output:

 replace()

It’s another JavaScript built-in method that takes two parameters, the first one is the value to be searched and the second parameter is the value that needs to be replaced in place of the first value. Syntax: string.replace(valueToSearch, valueToReplace) Here, valueToSearch represents the word that needs to be searched and valueToReplace is the new value that will take the position of valueToSearch. Return Value: A new string is returned with the replaced value. Let’s understand this better with an example: <html><body><p>Hello!! Welcome to our Website..</p><p>To replace "Website" with "Home" click the button.</p><button onclick="ReplaceMethod()">Replace</button><p id="div"></p><script>function ReplaceMethod() { var str = "Hello!! Welcome to our Website.."; var n = str.replace("Website","Home"); document.getElementById("div").innerHTML = n;}</script></body></html> In this, we simply replaced the word Website with Home using the replace method. Output:

 indexOf()

Another built-in JavaScript searching method for string that’s case sensitive is indexOf() method which searches the string and output is returned which shows the position of the first occurrence of the specified value. Syntax: string.indexOf(valueToSearch) OR string.indexOf(valueToSearch, startingIndex) Here, valueToSearch represents the word that needs to be searched and startingIndex is an optional parameter that specifies at which position the search needs to be started. It has a default value of 0. Return Value: It returns a number of the index where the value is found for the first time and if the value is not found, it returns -1. Example: <html><body><<p>Hello!! Welcome to our Website..</p><p>What's the index of the world "l"?</p> <button onclick="IndexOfMethod()">Search</button> <p></p> <script> function IndexOfMethod() { var str = "Hello!! Welcome to our Website.."; var n = str.indexOf("l"); document.getElementById("div").innerHTML = n; } </script> </body> </html> This shows that we’ll get the index where the letter “l” first occurred. Output: Here are some more examples to give better understanding of the method: let str = "Hello world, welcome to our website"; console.log(str.indexOf("e", 5)); // Returns 14 console.log(str.indexOf("Welcome")); // Returns -1 Here, in the first example the position was given 5, so it started searching from the 5th index. In the second example “Welcome” with capital W was written for the search. As it’s a case sensitive method so it returned -1. Output:

 lastIndexOf()

This JavaScript method searches the whole string and returns the position of the searched value where it last occured. This method is also case sensitive. Syntax: string.lastIndexOf(valueToSearch) OR string.lastIndexOf(valueToSearch, startingIndex) Here, valueToSearch represents the word that needs to be searched and startingIndex is an optional parameter that specifies at which position the search needs to be started. If you don’t mention startingIndex, the default value is always the length of the string. Return Value: It returns a number of the index where the value was found for the last time and in case it is not found then it returns -1. Example: let s= "A good cook could cook as much cookies as a good cook who could cook cookies"; console.log(s.lastIndexOf("cook")); // Returns 69 console.log(s.lastIndexOf("Cookies")); // Returns -1 console.log(s.lastIndexOf("co")); // Returns 69 console.log(s.lastIndexOf("a")); // Returns 42 console.log(s.lastIndexOf("much", 30)); // Returns 26 Here in these examples, we find the last occurrence of these specific words and return the position of these. As this method is case sensitive so writing “Cookies” instead of “cookies” gave us a -1 as an output. Output:

 Conclusion:

JavaScript provides us with various searching methods. These methods help in searching for specific words or the index where they occured. Some of these methods are case sensitive, so you’ve to be precise about the word you’re searching. All of these methods are accessible built-in and can easily be used by the user.

Regular Expressions

In our daily lives we continuously browse, search and find stuff on google, sometimes we find what we’re looking for, other times we fail. To make this search more precise, accurate regular expressions are there that help users with search and replace. Users can also use regular expressions for input validation or form fields, such as checking if the PIN entered consists of all numeric values or if it has some special characters. these regular expressions are objects that come as a built-in feature with the name “RegExp”. In this article we’ll discuss regular expressions, their syntax and how they’re used along with examples for your better understanding.

 Syntax of Regular Expression

There are two ways regular expressions can be written Using literal: The simplest way is enclosing the expression between slashes as shown below: const rE = /regularexpression/; Using Constructor function RegExp(): The other way of creating a regular expression is by using the constructor function “RegExp()” as shown below: const rE = new RegExp('regularexpression');

 How to Create a Regular Expression?

Creating regular expressions is simple, you can either use slashes or the RegExp() constructor. Below are the two examples using both of these methods of creating regular expression: let regexp = /hello there/; console.log(regexp); Output: Example: let regexp = new RegExp('hello there'); console.log(regexp); Output:

 Methods for Regular Expressions

Regular expressions are used for various purposes such as matching two strings, matching particular words in a string, searching for a particular word in strings, and replacing within a string. All of these have separate methods that can be used on the regular expression. Let’s see them one by one with example: test() method This method is used to match strings and as a result it returns the boolean value of true or false. Using this method, the user can verify if the particular string contains the match of a regular expression. Below is an example of two strings to show you the working of this method with regular expression: let regexp = /hello/; let check = regexp.test('hello world'); console.log(check); Output: Example: let regexp = /hello/; let check = regexp.test('hi world'); console.log(check); Output: match() method Another method that is used with the regular expression is match() methods that check a string and return an array of all the matches, in case no match found null is returned. Below is an example for the method match() along with the flag g which is a global flag that we will see in the article, it helps searching for all the matches in the string: let regexp = "Welcome to our website"; let check = console.log(regexp.match(/come/g)); Output: search() method Another useful method is the search() method in which we pass the value that needs to be searched in the string and when found the index of that word is returned as an output: let regexp = "Hey there, welcome!"; let check = console.log(regexp.search("there")); Output: replace() methodreplace() method is used to replace a specific value in the string. It takes in two parameter and searches the string with first parameter, when found replace it with the value to be replaced: let regexp = "Hey there, welcome!"; let check = console.log(regexp.replace("there", "you")); Output:

 Pattern Flags

To make searching more precise and accurate, regular expressions use flags along with the regular expression. Syntax: /regular expression/flags There are various flags present that change the behavior of searching, some of which are described below along with examples for better understanding. (i) ignore flag Many times when a user performs a search, it doesn’t provide accurate results for “hi” vs “Hi”, due to it being case sensitive. For this purpose the “i” ignore flag is used to ignore the cases and makes searching easier. let regexp = /hello/i; let check = regexp.test('Hello there'); console.log(check); // true Output: (g) global flag Mostly when using the method match() to search for a particular match in a string, it returns only the first match. But, with the use of the “g” global flag along with the method, it searches for all the matches in the string and returns an array of the matches found. let regexp = "The cook was cooking cookies"; let check = console.log(regexp.match(/cook/g)); Output: You can also use two flags together for a better result as shown below in this example: let regexp = `Name: John Age: 45 City: New York`; console.log( regexp.match(/a/gi) ); Output:

 Conclusion

Regular expression helps users to make searching and replacing stuff in a string or form validation easier. It’s used along with various methods and flags to find elements ignoring the case much faster and provide users with precise results. Here in this article we discussed Regular expressions along with their different syntax and methods, and how to make searching more accurate using flags. Examples are also provided for you to understand it better.

JavaScript Question Mark Operator

Normally in any programming language we represent the conditional statements with the traditional “if…else..” but these sometimes take up various lines of codes even for the simpler conditions. Hence, JavaScript provides us with the Question Mark(?) operator used for conditional statements. The question mark (?) operator is one of the most powerful features that JavaScript provides for conditional statements and when used along “:” it can act as “if…else..”. But that’s not the only way this operator is used. In this article we’ll discuss the question mark operator along with its usage with examples.

 Ways to Use Question Mark (?) Operator

The most common way of using the question mark operator is for conditional statements but that’s not the only usage of it. There are three main usages of the question mark operators as shown below:
    Ternary Operator Optional Chaining Nullish Coalescing
One of which we all are familiar with, but the other two are those only few know about so lets see and understand each along with examples.

 Ternary Operator

The term ternary simply means consisting of three parts and the question mark operator is also known as the ternary operator because unlike other operators such as “===” strictly equal, it is the only operator that takes in three parts. In the ternary operator we start with “?” in which we add a conditional statement on the left side of the operator and a value on the right side of the operator in case the condition is true. It’s followed by a colon “:” which is followed by a value that is to be returned in case the condition is false. Below is the syntax provided: Syntax: Conditional Statement ? True(value if true) : False (value if false) The ternary operator is used to replace the multiple lines of code of if else statement. Below is an example of if else statement along with it being replaced by a ternary operator to show how a conditional statement of if else can be changed to a single line code easily. if(20>12){ console.log("Yes")}else{ console.log("No")} The above line of code can be converted to a single line code: const biggerNum = (20 > 12) ? "Yes" : "No"; console.log(biggerNum); You can clearly see the difference between several lines of if-else condition is turned to a single line code using a ternary operator.

 Optional Chaining

Optional Chaining feature was introduced in 2020 that helps the user to handle an error in a more efficient manner. Let’s say you’ve a code that calls an object proprietary which does not exist and hence when the code is executed it’ll generate an error which could be due to missing value in your database or any other reason. For example look at the below example: const employee = { name: "Mark", workingSince: 2015} employee.write.salary(); Here, we’ve not defined the properties for the object and hence when we execute the code it’ll generate the below error: Now to avoid such errors, optional chaining was introduced through which we simply insert a question mark operator “?” between the property names as shown below: const employee = { name: "Mark", workingSince: 2015} employee.write?.salary(); Output: Through optional chaining it simply gave output “undefined” instead of throwing any errors and hence it’s one of the best features for developers to avoid such errors more efficiently.

 Nullish Coalescing

Sometimes we do not have a value for a property or it’s not available while writing the code. For example if we’re defining various users and we’ve a property image for each user and we don’t have the image available for those users. So, when the data is displayed the images for users will be blank which might look ugly and unprofessional. const employee = { name: "Mark", picture: undefined || "N/A"} console.log(employee); Output: But while dealing with “||” the logical operator OR, you might encounter some issues if you consider some values as usable, such as “ “ and “0”. For example we’ve declared a variable with value 0 or an empty string along with “||” logical OR operator, so the operator will consider the value as NULL or undefined and hence it’ll return some default value that we’ve fixed, as shown by the example below: const example1 = 0 || 'default string'; console.log(example1);const example2 = '' || 500; console.log(example2); Output: Here in the above example although we’ve set the values of both as 0 and empty string still it’s taking it as null and undefined and displaying the default value that we set. To solve this issue we use Nullish Coalescing or double question marks(??) as shown below: const example1 = 0 ?? 'default string'; console.log(example1);const example2 = '' ?? 500; console.log(example2); Output: This way the nullish coalescing is used which only accepts null and undefined values, other than that it always displays the right side values.

 Conclusion

Question mark operator is extremely useful as it is not only used for conditional statements but for other useful purposes. In this article we discussed question mark operators along with various ways of using it. First the traditional way is replacing the if-else conditions with it, but there are other ways as well to use it that we discussed in the article. Through question marks operators we can make our code more compact and handle errors in more efficient ways.

JavaScript methods for working with numbers

Another primitive data type that represents positive, negative, float, binary, octal, hexadecimal and exponential values in programming is a Number. JavaScript provides us with various number methods through which we can manipulate numeric values. In this article, we’ll learn various methods for working with numbers along with examples.

 Number Methods

To work with numbers we need specific methods that can help us manipulate and modify their values easily. For this, JavaScript provides us with various methods to work with numeric values. Following are some JavaScript number methods along with explanations and examples for your better understanding:

 Number()

Sometimes a user wants to convert a string into a number. For this purpose, Number() method is available. It’ll return a numeric value that’s converted from the argument passed. Syntax: Number(argument); Example: // Example 1 let a = '4' let num = Number(a) console.log(num) // Output: 4 console.log(num * 5) // Output: 20// Example 2 let b = '111.11' let num1 = Number(b) console.log(num1) // Output: 111.11// Example 3 let c = '44.65' let num2 = Number(c) console.log(num2) // Output: 44.65 Output: Furthermore, when boolean values true and false are passed, the program returns 1 and 0 as output. Example: console.log(Number(true)); // returns 1 console.log(Number(false)); // returns 0 Output:

 toString()

Now, to return a number as a string to String() method is available and It returns any numeric value as a string. Syntax: variable.toString(); Example: // Example 1 let a = 4444 let num = a.toString() console.log(num) // Output: 4444// Example 2 let b = 44.67 let num1 = b.toString() console.log(num1) // Output: 44.67// Example 3 let c = 101+99 let num2 = c.toString() console.log(num2) // Output: 200// Example 4 let d = 11 let num3 = d.toString(2) console.log(num3) // Output: 1011 Output: Here, in example 4, passing 2 as a parameter will return the binary value of the number.

 toLocaleString()

This method converts the number into a string that represents the local language format. Syntax: variable.toLocaleString(locales, options) It takes two parameters, locales which represent the languages in which you need to format your number. Second parameter is optional where you can define some properties. Example: let num = 37320932.001;//US English console.log(num.toLocaleString('en-US')); // Saudi Arabia (Arabic) console.log(num.toLocaleString('ar-SA')); Output:

 parseInt()

Similar to the Number() method, a string is provided as the argument and as a result it converts it into an integer value. Syntax: parseInt(argument); Example: // Example 1 let a = '15.3333' let num1 = parseInt(a) console.log(num1) // Output: 15// Example 2 let b = '14 hours' let num2 = parseInt(b) console.log(num2) // Output: 14// Example 3 let c = 'hour 5' let num3 = parseInt(c) console.log(num3) // Output: NaN Output: Here, in these examples it’s only returning the value before the decimal point. In the second example it returned only 14, but in the third NaN because it’s unable to find the number value in it.

 parseFloat()

This method takes in a string and returns the numeric value including the decimal value. Syntax: parseFloat(argument); Example: // Example 1 let a = '15.3333' let num1 = parseFloat(a) console.log(num1) // Output: 15.3333// Example 2 let b = '0.99998' let num2 = parseFloat(b) console.log(num2) // Output: 0.99998// Example 3 let c = '4.8 9.0' let num3 = parseFloat(c) console.log(num3) // Output: 4.8 Output: Here, in the third example it only returned the first number and not the second. It differs from parseInt() as it also returns the decimal value.

 toExponential()

This method is provided with a number as an argument and as an output an exponential value is returned in the form of a string. Syntax: variable.toExponential(); Example: // Example 1 let a = 15.3333 let num1 = a.toExponential(); console.log(num1) // Example 2 let b = 0.99998 let num2 = b.toExponential(); console.log(num2) // Example 3 let c = 4576.08976 let num3 = c.toExponential(2); console.log(num3) Output:

 toPrecision()

This method takes in an argument and returns the numeric value with the length given as the argument and If no argument is provided, it simply returns the same value. Syntax: variable.toPrecision(); Example: // Example 1 let a = 15.3333 let num1 = a.toPrecision(4); console.log(num1) // Example 2 let b = 0.99998 let num2 = b.toPrecision(1); console.log(num2) Output:

 toFixed()

This method rounds up a given number with the specified number of decimals. It takes in an optional parameter that represents the number of digits to be displayed after a decimal point. Syntax: variable.toFixed(); Example: let x = 15.8902; console.log(x.toFixed()); console.log(x.toFixed(2)); console.log(x.toFixed(3)); Output:

 Conclusion:

JavaScript comes with various number methods that help us to deal with numeric values.In this article, we learned various methods available for Numbers. These methods help us in changing the values of numbers or return them as a string. There are other methods also available with various functionalities. Through these methods, users can solve various problems more precisely. Thus, implementation of numerical algorithms becomes an easy task.

How to redirect to another webpage with javaScript

Page redirection is a technique in which a user attempts to open a particular URL, but instead that user is redirected to another URL. This could occur due to several reasons, some of which are listed below: Your content is moved to a new domain. So, all your visitors will be redirected to that new domain when they’re accessing the older domain. Your domain varies based on language, location etc. So, the user is redirected to the appropriate page based on these factors. Although you’ve moved your content to a different domain, search engines will still hold that content and URL within their index. So in case search engines know that old content has been moved to a new place and that a new place should take the primary spot in the index, you use client-side page redirection.

 Page Redirection with JavaScript

In JavaScript we can redirect to another page through the location object which is part of the window object and is accessed through the window.location property. This contains the URL information. There are several ways to redirect to another webpage using JavaScript. The most commonly used ones are location.href, location.assign and location.replace. Note: The browser console is used for the demonstration of examples in this article.

 Using window.location.href to redirect

Using location.href property, you assign the new URL as a String. This is useful when you want an event to occur if the user clicks a button or a link that will redirect them to a new page: <head> <script> function pageRedirect() { window.location.href = "https://www.google.com/"; } </script></head><body> <button type="button" onclick="pageRedirect()">Go to Google</button> <p><strong>Note:</strong> You can go to Google by clicking the button.</p></body>

 Using window.location.assign method to redirect

This method is similar to window.location.href, where you assign the URL. Through this the user can also track back to the previous page and it will create an entry in the history: <head> <script> function pageRedirect() { window.location.assign("https://www.google.com/"); } </script></head><body> <button type="button" onclick="pageRedirect()">Go to Google</button> <p><strong>Note:</strong> You can go to Google by clicking the button.</p></body>

 Using window.location.replace method to redirect

The Location.replace() method is used when you want to redirect to a new page without returning back to the older domain. The current page will not be saved in history and will be replaced with the new URL: <head> <script> function pageRedirect() { window.location.replace("https://www.google.com/"); } </script></head><body> <button type="button" onclick="pageRedirect()">Go to Google</button> <p><strong>Note:</strong> You can go to Google by clicking the button.</p></body> Another way of using it is through setTimeout() that redirects to a new page after a particular time assigned to it. <head> <script> function pageRedirect() { window.location.replace("https://www.google.com/"); } setTimeout("pageRedirect()", 2000); </script></head><body> <p><strong>Note:</strong>You can go to Google after 2 seconds.</p></body>

 Conclusion

You must have come across a situation where you clicked on the URL of a certain page but were redirected towards another page; this technique is called page redirecting and is commonly used by developers for several reasons. In this post, we’ve gone over different methods of redirecting to another webpage with JavaScript; the post also described the differences between the three redirecting methods, location.href, location.assign and location.replace. Using location.href and location.assign, the user can easily go back to the previous page as it creates an entry in the history. The location.replace redirects to a new webpage but it doesn’t create an entry in the history which is why the user can’t track back to the previous page.

How to create custom errors by using throw statements

While programming, the chances of something going wrong or causing an error are high. To represent these errors we need classes. Sometimes, users need to define their own error class suitable for their program. These errors vary from program to program but all of them have some basic properties like name, message, and stack. These errors can also come up with their own properties based on the function they’re serving. JavaScript allows users to create their own customized error using a throw statement. In this article, we will learn how to create custom errors using throw and how it works with examples.

 Custom Errors Using throw

Customizing errors allows you to act according to the specific error type without restoring the error message for a better understanding of the error. For example, in your program, you want to register people only above 18, and you want to throw an exception if someone enters a number below 18. This is done through a throw statement. Let’s understand this better. Syntax throw expression; Here, the expression specifies the type and value of the exception. The error can be a Number, String, Boolean, or Object in JavaScript. Example throw 'Above 18'; // output is an exception of data type stringthrow 404; // output is an exception of data type number with value 404throw false; // output is an exception of data type booleanthrow new Error('Important'); // output is an error of object type display message Important Custom errors can be generated by using throw with a try and catch block. Example of Custom throw error with try-catch <!DOCTYPE html><html><body><h2>JavaScript Custom Error with try catch</h2><p>Please enter your age if you're between 18-30</p><input id="demo" type="text"><button type="button" onclick="myFunction()">Check</button><p id="p"></p><script> function myFunction() { const message = document.getElementById("p"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "Empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 18) throw "below 18"; if(x >= 18 && x <= 30) throw "valid. User is between 18-30"; if(x > 30) throw "Above 30"; } catch(err) { message.innerHTML = "Input is " + err; } }</script></body></html> Output Firstly, when no input was entered it displayed the exception of Input is Empty, but when a number below 19 was entered it displayed the following exception: Now, when a number between 18-30 was entered: Furthermore, when the user entered an input that wasn’t a number: This shows how an exception was thrown depending on various inputs.

 Error Class

In JavaScript, we have an Error class that allows us to throw a user-defined exception. It has properties of name, message, and stack that a user can inherit from it and define their own methods inside it. Users can create a customized error class by extending their class with the Error class. Let’s understand this with the following example, but first, let’s see what the Error class looks like. Although it’s a built-in class, the following pseudo-code is given for better understanding: // The "pseudocode" for the built-in Error class definedclass Error { constructor(message) { this.msg= msg; //contains message this.name = "Error"; // (name differs according to the built in class that is being used) this.stack = <<strong>call</strong> stack>; // non-standard, but most environments support it }} Example of PageNotFound using Error ClassHere’s an example to demonstrate the working of custom error classes through extending the Error class. A PageNotFoundError class is created that displays the exception of a page not found along with the message and status code 404. class PageNotFoundError extends Error { constructor(message) { super(message); this.name = 'PageNotFoundError'; this.statusCode = 404; }}function throwAnError() { throw new PageNotFoundError('Not Found.');}try { throwAnError();} catch (error) { console.log(error.message); // 'Not Found.' console.log(error.name); // PageNotFoundError console.log(error.statusCode); // 404} Output In the above example, on line 1 we call the Parent Constructor because it sets the message property as well as the name and stack property of the Error. Furthermore, it’s obligatory to call super in the child constructor.

 Conclusion

User Customized errors are extremely helpful when a user wants to indicate a particular error according to the need of their program. In this article, we learned how to throw custom errors. Throw statement allows us to create errors according to our program flow. These expressions can be a String, Number, Boolean, or Object. Furthermore, we saw that the built-in Error class is available for users to customize their error class by simply extending it with the built-in Error class. This comes with its own properties that help users to even customize the parameters according to the behavior of their program.

How to Show or Hide an Element on Website using JavaScript

Throughout web development, users need to hide or show some elements. These elements can be a button, some animation, or a navigation bar etc. Most of the time the user wants a button or a navigation bar to be visible for the desktop viewpoint but not for the mobile viewpoint. With JavaScript, users can easily hide or show an element on the webpage, depending on the behavior of the user. In this article we’ll see how JavaScript is used for this purpose.

 Hiding and Displaying elements

Using JavaScript, we can hide or show an element on the webpage using: style.display style.visibility Let’s understand each of them separately with examples and then compare how the differ from each other: How to use style.display: The display property represents an element that should be displayed on your web page.. Using this user can hide the entire element, and the page is built as the previous element wasn’t there at all.

 Syntax:

document.getElementById("id-of-element").style.display = ""; Here in commas, a value should be defined for whether to display the content or not. Here’s an example:

 To Hide element: style.display = “none”:

<!DOCTYPE html><html><body> <p>Click the "Hide Me" button to hide the DIV element:</p> <div id = "div" > <img src="img1.jpg" > This is an apple </div> <button onclick="myFunction()">Hide Me</button> <script> function myFunction() { document.getElementById("div").style.display = "none"; } </script></body></html> As the user clicks on the button, the function is called to hide the element. This is done by assigning none value to style.display. Now look at the output, how the button occupied the space of the image. This is how display works, it hides the element entirely and rebuilds the page as if the element wasn’t there in the first place.

 To Show an element: style.display = “” or “block”:

<!DOCTYPE html> <html> <body> <p>Click the "Show me" button to show element the DIV element:</p> <div id = "div" > <img src="img2.jpg" id ="div2" style="display:none"> </div> <button onclick="myFunction()">Show Me</button> <script> function myFunction() { document.getElementById("div2").style.display = ''; } </script> </body> </html> Now similarly, in order to show the element the button moved and provided space to the element when display was changed from style.display =”none” to style.display = “”. Through these ways, the element will be displayed or completely hidden and not just its visibility. The page will be rebuilt according to these behaviours. How to use style.visibility : The style visibility works in the similar way, but the difference is that only the visibility of the element is hidden from the screen reader. This means that the element is not removed from the page flow, hence leaving space for it on the page.

 Syntax:

document.getElementById("id-of-element").style.visibility = ""; Here in commas, a value of “hidden” or “” no value should be defined for whether to display the content or not. To better understand this here’s an example: <!DOCTYPE html><html><body><p id="div">This is a paragraph.</p><button type="button" onclick="myFunction()">Hide content of paragraph</button><p id="div2">This is another paragraph.</p><script> function myFunction() { document.getElementById("div").style.visibility = "hidden"; }</script></body></html> Now, here when the button was clicked ato hide the visibility, it only hid it for the viewer’s eye. In this, the space on the web page was not occupied by the element. This shows how style.display and style.visibility differ.

 Conclusion

Everyone wants to hide or show some particular elements on their web page. In this how to guide, we learned ways to change the visibility of elements on the web page using JavaScript. There are two specific ways, but they differ from each other slightly. Using style.display the content gets hidden and its space is occupied by the other content. Whereas, using style.visibility, the content only is hidden for the reader, but it’s still there as its space can not be occupied by other elements. This is extremely useful for web developers, as developers want some content to be hidden and some to be displayed according to the viewpoint.

How can I encrypt/protect JavaScript source code

JavaScript is the most popular web programming language that comes with a lot of useful features. One of these features is immediate parsing i.e the browser executes the code as it downloads the content. This makes it browser interpreted or client side programming language. Therefore, it works on the client machine and hence making it difficult to hide the code from the client. Immediate parsing has its perks but it also comes with major downsides. As the source code is easily visible, everyone can read it. This can cause major security risks and hence the code needs to be protected. Sometimes you want to protect your JavaScript code from hackers, and sometimes you want to showcase an application but at the same time you don’t want your code to be copied. In this article, we’ll learn how to protect your JavaScript code and decrease the security risk.

 Protect JavaScript Code

Since you can’t hide your code but you can make it difficult to read for the user. But, if your code is easily readable and understandable to the user, the chances of your code being copied will be high. So, for this a number of techniques are used to alter your code without changing the functionality. The two most popular ways are: Obfuscate Minify First we will see what obfuscation is and tools available for it.

 What is Obfuscation

Obfuscation is the technique of going through your source code, changing the variables and rearranging them, breaking the application logic and hiding the original algorithm. An obfuscated code is difficult to understand and hence decreasing the security risk. Although the code can be deobfuscated, it’ll leave users with meaningless variables and hard to understand logic, with no comments, making it useless on large scale projects. There are various JavaScript obfuscator tools available online. Some of the best ones are listed down below: JavaScript Obfuscator UglifyJs Jscrambler Let’s look at them one by one, and the features they provide: JavaScript Obfuscator JavaScript Obfuscator comes with various functionality, from compressing the code, altering the flow to breaking the program’s logic and hiding the original algorithm. Furthermore, it confuses the user by applying dead/useless code that is not runnable and hence causing confusion to the reader. UglifyJs Another tool available for this purpose is Uglify, that makes the program “unintelligent” without altering the functionality. Goal is to make it unreadable by compressing and renaming the variables and functions. It’s also irreversible. Jscrambler Jscrambler increases the security of your code by adding various protecting layers like code locks and self-defending capabilities. Thus, making it unreadable for any stealer or hacker.

 What is minify

Minify, also known as minification, is simply compressing your code in such a way that it removes all unnecessary characters without changing the functionality. These characters include white spaces, comments, unnecessary parenthesis or variable declaration etc. This makes the code difficult to understand and hence decreasing the risk of being copied. There are several tools as well to perform this task, some of which are: Javascript compression tool Minify your JavaScript Javascript compression tool Javascript compression tool is available to compress your code by removing all unnecessary characters, comments, reducing its size and hence making it difficult to understand for the client. Minify your JavaScript This Javascript Minifer is available providing the same functionality. Users can upload their code and generate a minified version of it. Furthermore, users can download the generated file of their source code as well.

 Conclusion

Protection of code is an important aspect. In this article we saw why encryption or protection of your code is extremely important, the risk that comes with JavaScript and ways to reduce those risks. The main task for JavaScript developers is always protecting their source code and for this purpose various ways are available. It’s better to protect your code through various tools and technologies rather than leaving it unprotected and increasing security risks. Hence, tackling this issue beforehand will always put you ahead of the attackers and stealers.

How to Remove Elements from an Array

Arrays allow us to store similar kind of data in a single variable. We can then iterate over the data stored in the arrays and perform different functions to manipulate the data according to our needs. A single piece of data in an array is known as its element. JavaScript gives us the option to add and remove elements from an array after we have declared and initialized it. In this post we will only focus on the methods which can be used removing an element from an array. JavaScript provides numerous methods which can be used to remove array elements; In this post we will discuss four such methods. Here’s the list of the four most common methods for removing an array element: shift() pop() filter() splice() We will discuss them one by one in great detail. Note: I will use the console to demonstrate the examples present in this post.

 How to Remove an Element from the Beginning of an Array using the shift() method

JavaScript shift() method is commonly used to get rid of an element from the beginning of a JavaScript array. This method does not take any arguments. We can simply call it and it will remove an element from the beginning of the array and will shift every other element down by 1 index: var num = [0, 1, 2, 3, 4, 5]; num.shift(); console.log(num);

 How to get rid of an Array Element using the pop() method

JavaScript pop method can be used to get rid of an element from the end of a JavaScript Array. Similar to the shift() method It also does not take any argument: var num = [0, 1, 2, 3, 4, 5]; num.pop(); console.log(num);

 How to Remove Elements from an Array Using the filter() method

The filter() method can be used to remove elements of an array based on a certain condition; Applying the filter() method on the array does not change it rather it creates a new array consisting of the required elements. It takes a call back function as a parameter Now, as an example, we will use the filter() method to remove every element from an array that is greater than 2: var num = [0, 1, 2, 3, 4, 5];var num2 = num.filter(element => element < 3) console.log(num2); Now we will remove every element that less than 3: var num = [0, 1, 2, 3, 4, 5];var num2 = num.filter(element => element > 2) console.log(num2);

 How to Remove Elements from the middle of an Array using the splice() method

The splice() method/function can be used to insert or remove an element of an array. We will need to give two parameters to the splice() method if we want to use it to remove elements from an array. The first parameter will define the starting point from which the splice() method is going to remove the elements and the second element will specify the number of elements that will be removed from the array: var num = [1, 2, 3, 4, 5]; num.splice(2, 2); console.log(num);

 Conclusion

In this comprehensive guide we discussed four different methods of removing elements from an array. We can use the shift() and the pop() methods to remove items/elements from the start and end of an array object, respectively. If we need our original array to remain unchanged and want to create a new array which has elements that pass a certain condition then we should use the filter() method. The splice() method is best when it comes to removing an element from an array because it gives us control over the elements we want to remove. We can specify the index and number of elements that we want to remove in the splice() method.

How to Minify (Compress) JavaScript Code

To compress or minify a code means removing all the irrelevant characters from your source code without changing its functionality. These characters include white spaces, comments, new line characters, semicolons etc. But why is minimization of your code necessary? Well, it reduces the size to lesser kilobytes. Hence, making the loading of your website faster and providing the user an amazing experience. Various developers write well structured code with spaces and comments. This makes their code understandable. But, at the same time it creates extra space and hence increases the load time. This is why minimization of code is extremely useful as it reduces the size of the page. This minimized version provides better functionality without any additional network traffic.

 How is JavaScript code Minimized

JavaScript code can be minimized through various ways as listed below: Through the removal of white spaces and indentation Through the removal of extra characters from variable name Through the removal of new line characters Through the removal of unnecessary if, loops and variable decelerations Through optimizing your conditional statements and converting arrays into objects. Through the removal of comments Through the removal of unnecessary parentheses, semi-colons. Here’s an example of JavaScript before and after minimization: Before the code is of 8 lines: //This function takes in the name of color as a parameter//it logs the string of car with that color//by using the information passedfunction car(color){ console.log("Car color is "+color) } car("Red"); After, those 8 lines are minimized to a single line code: function car(c){console.log("Car color is "+c)}car("Red"); This is done through the removal of white spaces, extra comments; it will make it more optimized and speed up web page loading. But sometimes a user code consists of thousands lines and minifying it isn’t an easy task. That’s why there are various libraries and online tools that provide these functionalities.

 Online Tools to Minify your JavaScript Code:

Minification has become common in website designs and development. That’s why there are various tools that help you compress your code and save your precious time. Some of these are listed below:

Jscompress

This is a compression tool specifically for JavaScript, where users can upload multiple files at a time. This helps in saving the time of the user as well as combining all the files into a single code file an easier process. Hence, increasing the loading time of the page and making the website experience for the user better.

Javascript-minifier

This particular tool minifies both JavaScript and CSS. It’s easy to use, as users just have to paste their JavaScript code in the given box and click on the “Minify” button. This generates a minified version of your code that can also be downloaded as a file.

Minifycode

This tool offers minifiers for HTML, CSS and JavaScript. It’s similar to other minifiers where users just have to paste code and generate the minified version. But, it comes with an additional feature. It has a “Butifier” button that uncompress the minified code, making it easier to read for the user.

Google Closure Compiler

It’s an easy to use Google Closure Compiler that comes with various helpful optimization options. Various options are provided, whichever user wants to use according to their need. For example, if a user wants to optimize their code for whitespaces only or checking the syntax of their code. Furthermore, it also checks for any errors in the code, providing the user with best results.

 Conclusion

Minification of code refers to the removal of things that have no use in your code. This could include extra spaces, semi colons etc. It’s a useful practice and helps in the prevention of your source code being copied. In this article we saw why minimization of your code is necessary and various tools out there for this purpose. These tools provide users with various options to optimize their code on the bases of various factors such as speed, efficiency etc. The minimized version of your code will help in increasing the loading time of your webpage and decreasing the network traffic. Hence providing both the visitor and search engines better experience.

How to Read, Write and Parse JSON

The full form for JSON is JavaScript Object Notation and it is derived from the JavaScript programming language. A standard text format that defines the structured data is based on JavaScript object syntax. Transmission of data in web applications takes place through JSON. Have you heard about JavaScript object literal syntax? Yeah, JSON resembles it in a close manner. We are not limited to use it always with JavaScript.

 JSON vs JavaScript. How to compare them?

There is no ambiguity that JSON looks like JavaScript but, the easiest way to think of JSON is, as a data format, in resemblance with a text file. As JSON is inspired by JavaScript syntax, that’s the reason why they both look similar.

 Features of JSON

A feathery format is used for interchanging data The plain text that is being written object notation The purpose of sending the data between computers is achieved through JSON. It is language independent so you don’t have to worry about language compatibility in the case of JSON.

 Format of JSON

The JSON format is completely based on text and is derived from JavaScript object syntax. When you are dealing with JSON, you will surely tackle with the .json file, that’s where the JSON objects are being placed but they can also exist within the context of a program as a JSON object or string. Whenever you are dealing with a .json file, you are going to see the following: { "firstName": "John", "lastName": "Doe", "Online": true} In case, if you are interacting with a .jsor.htmlfile in which a JSON object is placed, you will see the following:

 JSON in string form

var userName = '{"firstName": "John", "lastName": "Doe", "location": "New York"}';

 How to read/write files

Nodejs provides us with a module that has a bunch of functionalities like reading files, write files, etc. It has many other tools that help us in working with the file system. It is known as “browserify-fs”. Now that we know what “browserify-fs” is, let’s install it. Use the following command in your editor to install “browserify-fs”. > npm install browserify-fs When it is installed successfully, import the browserify-fs module in the required program. We can now use different functions to write texts or read texts from a file. Now we can use the “browserify-fs” by importing it into our JavaScript file in the following manner: const fileSystem = require("browserify-fs") If you want to know more about how to import a library, visit our dedicated article for this:

 Prerequisite: How to import a library

Once you have successfully imported the browserify-fs library, let’s start with reading a JSON file.

 How to read a JSON file

Suppose we have a client.json file to which we want to read: //client.json{ "Name": "Mini Corp.", "Order_count": 83, "Address": "Little Havana"} Now, we will utilize fileSystem.readFile() to load the data from the client.json file. We will simply pass the path to our file and to receive the data, a call back function: const fileSystem = require("browserify-fs") fileSystem.readFile("./client.json", (err, data) => { if(err) { console.log("File reading failed", err) return } console.log("File data:", data)}) The contents of the file will be passed to the callback function after they have been successfully read. Now, to parse the fetched data into a pure JSON format, the JSON.parse() method will be used and the final code will look like this: const fileSystem = require("browserify-fs") fileSystem.readFile("./client.json", (err, data) => { if(err) { console.log("File can't be read", err) return } try{ const client = JSON.parse(data) console.log("client data is:", client) } catch(err) { console.log("Error parsing JSON string:", err) }}) Once you execute the above-provided code, the JSON data will be read and displayed on the console as we expected.

 How to write a JSON file

For writing data in an asynchronous way, we will use the fileSystem.writeFile() method. If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON.stringify method. This method will convert a JavaScript object into a JSON string which can be written to a file: const fileSystem = require("browserify-fs")const client = { "Name": "Mini Corp.", "Order_count": 83, "Address": "Little Havana"}const data = JSON.stringify(client) console.log(data) Above, a client object with our data has been created which is then turned into a string. Now, we will simply write our fileSystem.writeFile() method to write the JSON data into the newClient.json file: const fileSystem = require("browserify-fs")const client = { "Name": "Mini Corp.", "Order_count": 83, "Address": "Little Havana"}const data = JSON.stringify(client) fileSystem.writeFile("./newClient.json", data, err=>{ if(err){ console.log("Error writing file" ,err) } else { console.log('JSON data is written to the file successfully') }}) This is how we can write a JSON file using the fileSystem.writeFile() function.

 How to Parse a string to JSON

In JavaScript as well as JSON terminologies, parsing refers to the idea where a JSON string gets parsed and is then converted into a JavaScript value or an object described by the string. Before the resulting object is returned, transformation can be performed on it. As we did in our previous example of reading data from a JSON file, we simply fetched the data from the file, which was in the form of a string. After fetching the data, we parsed that string into the JSON, as shown below: Suppose we have some JSON data in string format: So this is how, using the JSON.parse() method, the string will be parsed into the JSON format.

 How to Parse JSON to string

Similarly, to parse JSON into a string, the JSON.stringify() method is used: const client = { "Name": "Mini Corp.", "Order_count": 83, "Address": "Little Havana"}const data = JSON.stringify(client) console.log(data) So this is how, using the JSON.stringify() method, the JSON can be parsed into the string format.

 Conclusion

The purpose of writing the article is to provide a complete explanation and a thorough description of how one can easily read, write and parse the JSON files. We were able to conclude the fact that the functionalities for reading and writing can easily be achieved by fileSystem.readFile and fileSystem.writeFile. We discussed the relative functionalities of both the components and explained how we can proceed by using these functions. Then we explained the method of parsing the JSON method in a precise way. Consequently, we were able to provide all the necessarily important details that were required to read, write and parse the JSON method.

How to Loop/Iterate Through an Array

Loops are key components of every programming language. They are used to run the same code or logic again and again in a cycle. Usually loops have an index value which is different each time the loop repeats. There are different kinds of loops available which help us iterate over an array. An array is a collection that is used to store different elements; An example of an array is: const names = ['John', 'Chris', 'Harry']; To get an element from this array we just provide index and the name of the array: console.log(names[2]); This will return “Harry” as the indexing starts from 0. We have seen that we can get an element from an array by specifying an index number. But it would be too hectic if there were 100 names in the above-mentioned array. The solution is using loops; loops can easily handle arrays with numerous entries. This post is focussing on how we can use JavaScript loops to iterate over an array to be an efficient programmer. Note: The browser console is used for the demonstration of examples in this article.

 How to iterate through an array using JavaScript for loop

A for loop is a loop which repeats an action as long as a certain condition is true. When the condition becomes false, the loop breaks. The syntax of for loop is similar to that in Java or C; The simplest for loop syntax is: for(initialize variable; some condition; variable increments/decrements){ //some code to be executed} Example of iterating through a for loop over an array is: const names = ['John', 'Chris', 'Harry'];for(let index = 0; index < names.length; index++){ console.log(names[2]);} We first declared an array named names, then a for loop and initialized a variable called index inside the for loop; This will act as the index for the array. After that, we put the condition that the loop should run till it is one less than array length i-e from 0 to 2 (3 times in total). The last parenthesis tells the loop that for every cycle increment the index by 1. Every cycle of the loop, we console logged the array elements one by one using the variable initialized that is index. To put it simply, the loop starts at the 0th index and then the length of the array is checked. If the condition is true then loop runs the block of code that is inside the parentheses which is console logging. After this, it increments “index” and then checks the condition again. Same cycle repeats until the specified condition is no longer true.

 How to iterate through an array using JavaScript while loop

Syntactically, JavaScript while loop is also similar to C or Java while loop. Example of iterating an array using while loop is: const names = ['John', 'Chris', 'Harry']; index=0; while(index<names.length){ console.log(names[index]); index++;}

 How to iterate through an array using JavaScript for/of loop

The for/of loop is also used to loop through the items/elements of an array: const names = ['John', 'Chris', 'Harry'];for (name of names) { console.log(name);}}

 How to iterate through an array using JavaScript forEach loop

The forEach() method calls or executes a specified callback function for each element in the array. It takes three arguments; the current item/element, index and the array itself. const names = ['John', 'Chris', 'Harry']; names.forEach(element => { console.log(element); }); In the example above we have used an arrow function which takes the current element of the array as an argument inside the .forEach() loop to console.log each element.

 How to iterate through an array using map method

The Map() method iterates over an array by creating a new array. For every element in the original array, it executes some function i.e. the arrow function with num as an argument in the below given example. It doesn’t change the original array. Now suppose we have an array of numbers from 1 to 5. We want each number to multiply by 2. We can achieve this as follows: let table1 = [1,2,3,4,5]; let table2 = table1.map(num => num * 2); console.log(table2);

 How to iterate through an array using every method

The every() method tests whether every element of the array passes a condition implemented by the provided function; it executes a function once for every element. It returns either true or false depending upon whether every element passed the test or not: const isLessThanTen = (currentValue) => currentValue < 10;const arr = [1, 3, 4, 3, 5, 7]; console.log(arr.every(isLessThanTen)); Now if we change the array in the above example: const arr = [1, 3, 16, 3, 5, 7];

 Conclusion

In JavaScript arrays are a data type which are used to store similar kinds of data; this data can be easily accessed and manipulated by using different loops and methods provided by JavaScript. In this post we covered the basics of iterating over an array. We also discussed iterating through an array from for, while, for/of, forEach() loop, map() and every() method. These are not the only methods that can be used to iterate over an array. There are dozens more. The ones we discussed are the widely-used methods by the developers iterating over an array.

How to get elements from the DOM

JavaScript is used to add interactivity to a static HTML page; but to add interactivity it needs to access the HTML elements present in the DOM. JavaScript offers a number of methods to access the HTML elements present in DOM. Here we will discuss most of them in great detail:

 How to access a DOM element by its ID using JavaScript

One of the most common methods to access an element in HTML DOM is getElementById() which accesses an element based on the value of its ID attribute. The value of the ID attributes are supposed to be unique and no two elements on a single HTML page should have similar IDs. Even if there are multiple elements that have the same ID, the getElementById() method returns only one element (the first element with that ID in the HTML file). Now we will take a look at an example to better understand how the getElementById() method works. Note: The browser console is used for the demonstration of examples in this article. The following HTML file will be used for this example; The JavaScript will be added within the <script> tags which are specifically used to embed JavaScript code directly inside an HTML file. <!DOCTYPE html><html lang="en"><head><title>Accessing DOM Elements</title><style> body { max-width: 500px; } p { padding: 5px; border: 2px solid black; }</style></head><body><h1>How to get Elements from the DOM?</h1><h2>How to access a DOM element by its ID?</h2><p id="example-id">getElementById()</p><script></script></body></html> In the above given HTML file we have a paragraph with a unique id i.e. example-id. If we want to access this paragraph element, we can use the getElementById() method: <script>const paragraph = document.getElementById('example-id'); console.log(paragraph);</script> We can now use the newly created paragraph variable to manipulate the example-id element directly from JavaScript e.g if we want to change the background and text-color of the paragraph then: <script>const paragraph = document.getElementById('example-id'); paragraph.style.color = 'white'; paragraph.style.backgroundColor = 'black';</script>

 How to access DOM elements by their class

The getElementsByClassName() method can be used to get multiple elements that have the same class attribute value. To show how the getElementsByClassName() method works we will modify our HTML file in the following way: <!DOCTYPE html><html lang="en"><head><title>Accessing DOM Elements</title><style> body { max-width: 500px; } p { padding: 5px; border: 2px solid black; }</style></head><body><h1>How to get Elements from the DOM?</h1><h2 class="example-class">How to access DOM elements by their class?</h2><p class="example-class">getElementsByClassName()</p><script>const sameClassElements = document.getElementsByClassName('example-class'); console.log(sameClassElements);</script></body></html> The getElementsByClassName() method returns all the elements that have a specific class in the form of an array. So if we want to modify only one of the elements present inside the returned array we will need to access it with its index number: <script>const sameClassElements = document.getElementsByClassName('example-class'); sameClassElements[0].style.color = 'blue';</script> We can use a for loop if we want to apply the same changes to all the elements of the array: <script>const sameClassElements = document.getElementsByClassName('example-class');for (let index = 0; index < sameClassElements.length; index++) { sameClassElements[index].style.color = 'blue';}</script>

 How to access DOM elements by their Tag

JavaScript also provides the getElementsByTagName() method which can be used to access all the elements that have the same HTML tag: <!DOCTYPE html><html lang="en"><head><title>Accessing DOM Elements</title></head><body><h3>How to get Elements from the DOM?</h3><ul><li>getElementById() method</li><li>getElementsByClassName() method</li><li>getElementsByName() method</li><li>getElementsByTagName() method</li><li>querySelector() method</li><li>querySelectorAll() method</li></ul><script>const sameTagElements = document.getElementsByTagName('li') console.log(sameTagElements);</script></body></html> We can again use a loop to apply the same changes to all the elements present within the new array: <script>const sameTagElements = document.getElementsByTagName('li')for (let index = 0; index < sameTagElements.length; index++) { sameTagElements[index].style.fontFamily = 'sans-serif';}</script>

 How to access DOM elements by using the Query Selectors methods

JavaScript also has the querySelector() and the querySelectorAll() methods which can be used to access HTML DOM elements. To access a single element we can use the querySelector() method; if there are multiple elements with the same ID or Class then the querySelector() method returns the first element: <!DOCTYPE html><html lang="en"><head><title>Accessing DOM Elements</title></head><body><h3>How to get Elements from the DOM?</h3><p id="example">getElementById() method</p><p class="example">getElementsByClassName() method</p><p>getElementsByName() method</p><p>getElementsByTagName() method</p><p>querySelector() method</p><p>querySelectorAll() method</p><script>const paragraphOne = document.querySelector('#example');const paragraphTwo = document.querySelector('.example'); console.log(paragraphOne); console.log(paragraphTwo);</script></body></html> The # sign is the selector for the ID attribute whereas the . sign is the selector for the class attribute. The querySelectorAll() method returns an array containing all the DOM elements with a specific class name or an ID: <!DOCTYPE html><html lang="en"><head><title>Accessing DOM Elements</title></head><body><h3>How to get Elements from the DOM?</h3><p id="example-id">getElementById() method</p><p id="example-id">getElementsByClassName() method</p><p id="example-id">getElementsByName() method</p><p id="example-id">getElementsByTagName() method</p><p id="example-id">querySelector() method</p><p id="example-id">querySelectorAll() method</p><script>const paragraphs = document.querySelectorAll('#example-id'); console.log(paragraphs);</script></body></html> We can perform different methods such as .forEach() method on the arrays returned by the querySelectorAll(). These methods do not work with the arrays returned by getElement methods.

 Conclusion

Accessing HTML DOM elements and making them interactive through JavaScript is the most basic yet an essential part of any Front-end Develoepr’s work. Here we have listed the five most common methods used for accessing DOM elements.

What is a Promise Object

In JavaScript the promise objects are used to work with the asynchronous operations. The concept of promise may sound complicated at first but in reality they are quite simple; We can understand JavaScript promises by comparing them with real world promises using layman’s terms. In everyday life we make promises to show our commitment. Similarly we make a promise object when we need to be committed to executing a block of code. For example, when we send a request to fetch data from an API through our code, the API takes time to respond. In the meantime the JavaScript interpreter moves onto the next block of code but we want to execute some piece of code after the fulfilment or rejection of the response. Now, if we use the promise object, we can execute the desired line of codes upon the fulfilment or rejection of the API response. The JavaScript promise objects can have three different states i.e: Pending Fulfilled Rejected The promise is in pending state when the result of the promise object is undefined; it is fulfilled when the result has a value and rejected when the result is an error. For instance, In the above example if we have sent the request to the API and are awaiting for the data then the promise is in pending state. If the API successfully sends the data then the promise is fulfilled and if the code cannot connect with the API then the promise has been rejected.

 What are promises

As mentioned above, asynchronous operations are handled through promises. Asynchronous JavaScript mainly refers to the functions that are running in parallel with the main program. In JavaScript events and callback functions were used to handle asynchronous operation before promises. Promises were added in the ES6 version of JavaScript in 2015. Although callback functions and events were useful they still had their limitations. Callback hell was the biggest drawback of the usage of callback functions. Promises are perfect for handling asynchronous operations as they can handle several asynchronous operations and are way better at handling errors than events and callbacks.

 How Promises Work

Asynchronous functions are functions that run parallel to the main program. These functions work separately from the main program and notify the calling thread of their success, failure or progress. The promise object has one of three states: pending: It is the state of the promise object between its initialization and completion. fulfilled/resolved: It is the state which indicates that the operation of the promise object was successful. Rejected: It is the state which indicates that the operation of the promise object was unsuccessful.

 Creating a simple promise object

Here we will learn to create a promise object in just a few simple steps:
    In JavaScript a promise object is created using a constructor “new Promise()”. This constructor takes a call back function with two arguments as an argument. The code that is required in order to perform the promised task is written in the body of the call back function. If the task is successfully performed then the promise is resolved/fulfilled; otherwise the promise is rejected/unfulfilled. There are two methods associated with the promise object, the then() and the catch() method. These methods are (respectively) called if the promise is resolved or rejected.
Note: The browser console is used for the demonstration of examples in this article. JavaScript promises are created by using the new Promise() constructor: const myPromise = new Promise(); The new Promise takes two different parameters. One of these parameters is for success (incase the promise is resolved) and the other one is for failure (incase the promise gets rejected): const myPromise = new Promise((resolve, reject) => { // condition// condition}); Finally, we define the body of the promise object. We give it a condition which will only be met if the promise is resolved: const myPromise = new Promise((resolve, reject) => { let condition = true; if(condition) { resolve('Promise is resolved.'); } else { reject('Promise is rejected.'); }}); Now let’s learn to use our newly created promise object. There can only be two different end results for a promise object; it can either be a resolved or a rejected promise. then() method : The then() method defines what will happen next if a promise gets resolved. myPromise.then(); In this example we are using the then() method to log a message (that we got from the Promise) to the console. myPromise.then((message) => { console.log(message);}); catch() method : Similarly, the catch() method defines what will happen next if a promise fails. myPromise.then((message) => { console.log(message);}).catch((message) => { console.log(message);}); It can be written in two different ways; separately or in combination with the then() method. In case the promise is unfulfilled, it will execute the catch() method and this time a different message will be shown on the console.

 Conclusion

Promises are objects that are used as an alternative of callback functions and events when handling asynchronous operations. Promises can have three different states i.e. pending, fulfilled or unfulfilled. In the pending state the promise object is awaiting the value thus it has no value. In the fulfilled state it has the resolved value and in the unfulfilled state it has the reason why the promise was not resolved. This post was a thorough guide about promise objects.

What is a Prototype

JavaScript is a dynamic and prototype based language hence prototypes are one of the most important concepts of JavaScript. Let’s first discuss why we need prototypes.

 Why do we need prototypes?

As mentioned earlier, JavaScript is a dynamic language which means we can add properties to an object anytime we want. Let us go through an example to explain this: function Player() { this.name = 'Hazard'; this.club = 'Chelsea';}var player1 = new Player(); player1.age = 30; alert(player1.age);var player2 = new Player(); alert(player2.age); In this Example, we gave another property to the object player. However, the first object i-e player1 will have age property but not the second object i-e player2. The reason for this is that the age property is only defined for the player1 object. We can see the player2 object shows undefined in the below output of the above example: Now that we know what problem we are facing, the question arises: what is the solution? The Solution to this problem is “prototype”.

 Solution

Prototypes are a built-in feature of JavaScript. Each time you create a JavaScript function, JavaScript automatically adds a prototype to that function. We can say that a prototype is an object that allows you to add new properties to an existing object. In short, Prototypes contain a base class of all objects, helping us achieve inheritance. We can attach additional properties to the prototype object which will then be shared across all the instances. Now we will use prototype property in the above example to solve the problem of sharing age property to all the objects i-e player1 and player2. function Player() { this.name = 'Hazard'; this.club = 'Chelsea';} Player.prototype.age=30;var player1 = new Player(); alert(player1.age);var player2 = new Player(); alert(player2.age); We will see that both players’ ages will be 30 now. The output is shown below: To put simply, the prototype property of JavaScript helps us in adding new properties to object constructors as shown in the above example.

 Prototype Property of an object

Every object that is initiated using the literal syntax or initiated using the constructor syntax using the new keyword, includes __proto__ property. This will point to the prototype object which created this object. If you wish to see the prototype property of an object, we can see it in the debugging developer tool. In the below example we will implement it and will view it in the console window.

 Example

function Player() { this.name = 'Hazard'; this.club = 'Chelsea';}var playerObject=new Player();//console window console.log(Player.prototype); console.log(playerObject.prototype); console.log(playerObject.__proto__); console.log(typeof Player); console.log(); In this example we can see that the function prototype property is accessed using the function name which is Player.prototype. We can also see in this example that the prototype property is not exposed to the object, we can only access it using the “__proto__”.

 Object’s Prototype

In the previous example, we saw that the object prototype property is undefined which means it is invisible. We can use the Object.getPrototypeOf(obj) method instead of the one we used i-e “__proto__”. By this it won’t be undefined and we will be able to access the prototype object. function Player() { this.name = 'Hazard'; this.club = 'Chelsea';}var playerObject=new Player(); Player.prototype.selected= function(){ alert("Selected for today's team");}var player1 = new Player();var checkingProto= Object.getPrototypeOf(player1);//this will return player1 prototype object alert(checkingProto.constructor);//this will return player1 function that is selected

 Conclusion

In this article we mainly discussed the basic concept of Prototypes. We dug a little deeper and discussed what is a prototype. We also discussed a problem and gave the solution using the prototype. Apart from this we discussed finding object properties and methods using prototypes. All of this was demonstrated with the help of examples to develop better understanding of the concept.

What’s new ES6?

JavaScript is considered to be among the most widely used and popular scripting languages; It was invented in 1995 and originally called Mocha but eventually became JavaScript. The language JavaScript was invented by BrendanEich and turned into the ECMA standard; ES1, ES2, ES3, ES5, and ES6 are numerous versions of ECMAScript. JavaScript ES6 is a standard for ensuring web page interoperability in various web browsers. ES6 is the 6th version of JavaScript programming language. It’s a major improvement in the JavaScript language, adding more features to facilitate large-scale software development. Few features of the ES6 script are not supported by all the browsers, but most are supported; almost all the famous web browsers support all the features of ES6. Transpiler software can be used to transform ES6 code into ES5, which is the older version of JavaScript and hence more compatible with browsers. In this article, we look at some changes ES6 brought.

 Features of ES6 JavaScript

Constants known as Immutable Variables : ES6 now supports the notion of constant variables. The value of these variables cannot be modified. An error will be triggered if someone tries to redefine the variable in the similar scope: const pi = Math.PI;// Output: Value of PI console.log(pi); pi = 4;// TypeError: Assignment to constant variable. console.log(pi); {const pi = Math.PI;// Output: Value of PI console.log(pi);}const pi = 4;// Output: 4 (without any error as it is out of the scope) console.log(pi); If an object has been declared using const, its keys cannot be changed. However its values can be changed: const user = { name: "Steve", age: 13 } user = { userName: "Harry", grade: "3rd" } // TypeError: Assignment to constant variable. const user = { name: "Steve", age: 13 } user.name = "Harry"; console.log(user);

 Rules of Blocked Scope Functions & Variables

Another important new feature of ES6 is that variables can be declared through let and const which follow block-scoped rules. Through this block-scoped rule, the variable holds its value until the end of the block. The value of the outer block will be restored after the inner block: let a = 5;// Output: 5 console.log(a);{ let a = 4; // Output: 4 console.log(a);}// Output: 5 console.log(a);

 Arrow Functions

ES6 also supports arrow functions that are almost the same as JavaScript traditional functions but are more compact. In the example below we have made an arrow function which takes a number as an argument and returns the value of its square: sq = a => a*a; console.log(sq(5)); The arrow functions do have their limitations and cannot be used everywhere.

 Handling of Function Parameters

ES6 gives us the option to set default values for the parameters of a function. If no arguments are given when calling the function then the default parameters are used: function sq(a = 5, b = 3) { console.log(a + " + " + b + " = " + (a+b));} sq(5, 9); sq();

 Parameters of Rest Function

Rest parameters function is another feature of ES6. This feature helps you to receive any number of arguments whenever the function is called. The syntax shown below allows you to capture the remaining arguments after the defined argument in an array: function restParams(a, b, ...params) { console.log(a); console.log(b); console.log(params);} restParams(1,2,3,4,5,6,7,8,9);

 Template literals

A string template or template literal refers to interpolate variables and expressions as strings using a Perl syntax. In simpler words a string can be enclosed in backticks (`) and these strings can include (interpolated) expressions by using the ${···} syntax: var firstName = 'John';var lastName = 'Doe'; console.log(`My name is ${firstName} ${lastName}`);

 Properties of Object

ES6 provided a new syntax for the creation of objects. Here is the example: var firstName = 'John';var lastName = 'Doe';var id = 03;var department = 'Education';var employeeData = {firstName, lastName, id, department}; console.log(employeeData);

 Syntax of Formal Class Definition

JavaScript ES6 supports formal class definition syntax. It’s a simple syntactic sugar for prototype based classes that’s already available, but it helps improve code clarity. This means that this hasn’t added a new object model. class circle { constructor(radius) { this.radius = radius; }}var c = new circle(8);

 Methods Declaration

ES6 JavaScript provides a simpler way to declare methods. Earlier, in ES5, we had to mention the keyword “function” along with the function name while defining it. However, in ES6, we can use the arrow function and we are not obliged to write the “function” keyword. Here is the example: In ES5 var diameter = function(radius) { let dia = 2*radius; return dia;}; diameter(8); In ES6 var diameter = (radius) => { let dia = 2*radius; return dia;}; diameter(8); For/Of Loops Using for/of, you can iterate over iterable data structures such as arrays, strings, maps etc: var num = [5, 6, 7, 8, 9];for (let d of num) { console.log(d);}

 Conclusion

ES6 is the second major revision of JavaScript which was released back in 2015. There have been yearly additions to JavaScript in ES7, ES8, ES9 and so on but these new versions have not brought any significant change. In this article, we briefly explained what ES6 JavaScript is, the benefits of the ES6 version and some of the new features introduced in version ES6.

How to encode or decode a string using base64

Base64 encoding is an interesting way of representing information which is used to transform binary data into a string consisting of alphabets, digits and some special characters. Base64 is typically used to encode data that may be corrupted during transfer. Before eight bit bytes became a standard many systems such as SMTP (Email) used seven, six and even three bit bytes which led to data being lost during transfer between systems. So a new encoding scheme was developed which represented binary data in the form of text strings which could easily be transferred between systems without any damage to the data. Base64 is commonly used to encode the binary data of email attachments such as images and documents. It is also used to encode the images and audio files embedded in a webpage. Base64 was also invented to reduce the expenses of data transfer between systems. In Base64 each character replaces six digits of binary which makes it a more efficient way of data transfer and reduces its cost. 01101011 00000001 01001010 10101001 01010101 01001010 10101111 11000011 00110110 10110101 01010101 01010010 01101010 01101101 01101100 10101010 10101010 10110010 11011011 01011011 00101011 00101100 11001010 10110101 01010101 01010100 10010110 01010101 10111010 10101101 01011010 10101011 10101011 10011010 10101010 00000000 01101011 00000001 01001010 10101001 01010101 01001010 10101111 11000011 00110110 10110101 01010101 01010010 01101010 10101010 00000000 10101010 10101010 10110010 00000001 01011011 00101011 00101100 11001010 10110101 01010101 01010100 10010110 01010101 10111010 10101101 01011010 10101011 10101011 10011010 10101010 00000000 10101010 10101010 10110010 11000011 00110110 For example, the binary data given above can be reduced to this short string using Base64 encoding: awFKqVVKr8M2tVVSam1sqqqy21srLMq1VVSWVbqtWqurmqoAawFKqVVKr8M2tVVSaqoAqqqyAVsrLMq1VVSWVbqtWqurmqoAqqqywzY=

 How to encode and decode a string using Base64

There are two different functions available named btoa and atob which enable programmers to encode or decode a string; These functions are supported by almost all major web browsers. In this article we will extensively discuss both btoa and atob functions; but first let’s discuss the btoa function:

 How to encode a string using Base64

JavaScript has a built-in function named btoa which can be used to encode a string into a Base64 string: var originalStr = "Welcome to Linux Hint!"; encodedStr = btoa(originalStr); console.log(encodedStr);

 How to decode a Base64 string

JavaScript provides the atob function to decode a Base64 string into a normal string: var originalStr = "Welcome to Linux Hint!"; encodedStr = btoa(originalStr); console.log(encodedStr); decodedStr = atob(encodedStr); console.log(decodedStr);

 Conclusion

Base64 is a data representation format which converts binary data into a special string of characters, digits and special characters; each character in Base64 string replaces 6 binary digits. Base64 does not conceal data, it only transforms it from one format to another for easier transfer between different systems. The Base64 encoded string should be treated as plain text; it does not protect data from the man in the middle attacks. In this post we learned to encode and decode strings using Base64.

How to create a countdown timer

Countdown timers are a kind of a virtual clocks which count the time until a specific date to mark the start or end of a special occasion. They were mostly used on the landing page of new upcoming websites but now they have found their way into e-commerce websites. The “time is running out” element on the countdown pages helps create urgency to generate more conversions on E-commerce websites. Timers can also be used on websites or blogs in order to display a countdown for special events i.e. anniversaries, birthdays, meetings etc. Countdown timers can also be used to count down the time till an offer becomes available In this how-to guide we will make a time counter in vanilla JavaScript, instead of using third party libraries or plugins. The benefits of creating the countdown clock in vanilla JavaScript are as follows: The code is lighter because there are no dependencies. Improves website performance as there is no need to load any external stylesheets and scripts.

 How to create a countdown timer

The basics of the countdown timer are as follows:

 Set the End Date of the timer

The first step of creating a countdown timer is to set the end date of the timer. In this step we will declare a variable and assign it the value of the end date of our timer using the Date object: var endDate = new Date('Aug 20, 2021 00:00:00').getTime(); In the above example we have used the .getTime() method; this is because the .getTime() method converts the Date into a more usable format. It returns the number of milliseconds that have passed since the midnight of Jan 1, 1970 which makes it easier to perform mathematical operations on the endDate variable.

 Make a Timing Event funcion

Now we will make a setInterval() function which will repeatedly execute the code inside it after the specified time interval. This is because we want to update our timer after every second: var countDownTimer = setInterval(() => {// All of the JavaScript code mentioned below goes inside this function}, 1000); The setInterval() function takes the interval argument in milliseconds; as there are 1000 milliseconds inside a second and we want to refresh the counter after every second, we have given 1000 as the interval of the timing event function.

 Calculating The Time

Now we will write code inside the setInterval() function. In this step we will calculate the time remaining till the end time of the counter: var now = new Date().getTime(); var remainingTime = endDate - now; Now the value of the remaining time present in the variable remainingTime is in the form of milliseconds but we want to show the remaining number of Days, Hours, Minutes and Seconds so we will need to convert the number of milliseconds into our required time periods: const second = 1000;const minute = second * 60;const hour = minute * 60;const day = hour * 24; daysLeft = Math.trunc(remainingTime / day); hoursLeft = Math.trunc((remainingTime % day) / hour); minutesLeft = Math.trunc((remainingTime % hour) / minute); secondsLeft = Math.trunc((remainingTime % minute) / second); There are 1,000 milliseconds inside a second, 60,000 milliseconds (1000*60) inside a minute, 3,600,000 milliseconds (1000*60*60) in an hour and 86,400,000 milliseconds (1000*60*60*24) in a day. We have calculated the days left by dividing the amount of milliseconds present in remainingTime by the amount of milliseconds in one day; If there are 86,400,000 milliseconds left then daysLeft will be equal to one (86,400,000/86,400,000), if there are 172,800,000 milliseconds left then daysLeft will be equal to 2 (172,800,000/86,400,000) and so on. The number returned by the (remainingTime / day) operation will most often be a decimal number but we only need the whole number part so we have used the Math.trun() method. To calculate the hoursLeft we first got rid of the days by using the modulus operator. Then we calculated the hours from the remaining time. We can calculate the minutesLeft and secondsLeft variables similarly.

 Displaying The Timer

In this step we will add some code (tags) into the HTML body; then we will access those tags in the setInterval() function and modify them to show the timer on the webpage: <p id="days"></p><p id="hours"></p><p id="minutes"></p><p id="seconds"></p> Inside the setInterval() function: document.querySelector('#days').innerHTML = daysLeft + ' Days'; document.querySelector('#hours').innerHTML = hoursLeft + ' Hours'; document.querySelector('#minutes').innerHTML = minutesLeft + ' Minutes'; document.querySelector('#seconds').innerHTML = secondsLeft + ' Seconds'; Now we will add some more code in the setInterval() function which will be executed in case the timer is up: if (remainingTime <= 0) { document.write('Time Up!');} All in all the HTML file for a countdown timer should look something like this: <!DOCTYPE HTML><html><head></head><body><p id="days"></p><p id="hours"></p><p id="minutes"></p><p id="seconds"></p><script> var endDate = new Date('Aug 20, 2021 00:00:00').getTime(); var countDownTimer = setInterval(() => { var now = new Date().getTime(); var remainingTime = endDate - now;const second = 1000;const minute = second * 60;const hour = minute * 60;const day = hour * 24; daysLeft = Math.trunc(remainingTime / day); hoursLeft = Math.trunc((remainingTime % day) / hour); minutesLeft = Math.trunc((remainingTime % hour) / minute); secondsLeft = Math.trunc((remainingTime % minute) / second); document.querySelector('#days').innerHTML = daysLeft + ' Days'; document.querySelector('#hours').innerHTML = hoursLeft + ' Hours'; document.querySelector('#minutes').innerHTML = minutesLeft + ' Minutes'; document.querySelector('#seconds').innerHTML = secondsLeft + ' Seconds';if (remainingTime <= 0) { document.write('Time Up!');}}, 1000);</script></body></html> A countdown timer has been successfully made; now you can style it using CSS.

 Conclusion

Countdown timers are used by soon to be live websites as well as many ecommerce websites. The ecommerce websites use timers to persuade the customer to make quick decisions. The resolution of this post was to explore the making of a countdown timer.

How to Convert a Number into a String

Management of Data is a crucial task for any programmer; JavaScript is a very versatile programming language which offers multiple built-in methods to convert data into different data types. The .tostring() is one of these methods. The .tostring() method can be used to convert the data type of a variable from a number to a string. In this how-to guide we will learn to convert a number into a string using the .tostring() method. The .tostring() method is commonly used in combination with numbers to convert them into strings. It takes a single optional parameter:

 Syntax:

num.toString(base) Parameter: The .tostring() method takes a single optional parameter. This parameter will specify the base of the number which will be stored in the string. Return Value: The .tostring() method returns a string which contains the specified number object converted to the specified base.

 How to change a number into a string

We just need to invoke the .toString() method without passing any parameters, if we only want to represent the number in its string form without changing its base: var num = 549; var str = num.toString(); console.log(num); console.log(typeof num); console.log(str); console.log(typeof str);

 How to convert a number to a string with base 2(binary)

If we want to convert a number into a string as well as to a different base, let’s say 2, then we need to pass a parameter as well. In this case we will pass 2 as we want to convert the number into binary: var num = 549; var str = num.toString(2); console.log(str);

 How to convert a number to a string with base 8(octal)

To convert the number into a string as well as into a base 8 number we will pass 8 as a parameter: var num = 549; var str = num.toString(8); console.log(str);

 How to convert a number to a string with base 16(HexaDecimal)

Similarly to convert the number into a HexaDecimal while also converting it into a string we need to invoke the .tostring() method and pass 16 as a parameter to it: var num = 549; var str = num.toString(16); console.log(str);

 How to Use Other Data Types with the toString() Method

The .toString() method is also used to change data types other than numbers into their string representations. Let’s look at an example where an array has been converted into its string representation: var arr = [ "John", "Jerry" ]; var str = arr.toString(); console.log(str); Similarly we can convert any data type into a string: var bool = true; var str = bool.toString(); console.log(str); console.log(typeof str);

 Conclusion

The .toString() method takes a number and changes it into a string. It takes a single optional parameter which can be used to convert the number to a different base. working with strings is a lot easier than numbers in some cases so converting a number into a string is not an absurd idea. In this guide we learned to convert a number into a string data type using the .tostring() method. Moreover we also learned to convert other data types such as objects and booleans into strings as well.

How to add elements into an array

Arrays are data structures which are used to keep multiple values in a variable. A single JavaScript array can have multiple element types stored in it. It can be modified even after it has been declared and initialized. JavaScript arrays offer a lot of built-in methods which can be used to access and manipulate data stored inside them. In this how-to guide we will discuss four different methods which can be used to add elements into JavaScript arrays. Here’s a list of the four methods we will discuss in this article:
    unshift() push() concat() splice()
Note: I will use the console to demonstrate the examples present in this post.

 How to insert items to the start/beginning of an Array Using the unshift method

The unshift function is commonly used to add/insert elements to the start/beginning of an array. It is quite simple to use the unshift() method, just pass the element value you want to add to an array to the unshift() method and when the unshift() function is invoked, the element will be added to the array, and the index of the array will be automatically shifted down: var num = [1, 2, 3, 4, 5]; num.unshift(0); console.log(num); You can also add multiple values to an array using the unshift() method: var num = [1, 2, 3, 4, 5]; num.unshift(-5, -4, -3, -2, -1, 0); console.log(num);

 How to Add Elements to the End of an Array Using the push method

The push() method is used to insert items/elements to the last index of an Array. It takes one or more arguments (separated by commas) and adds them to the end of the specified array: var num = [1, 2, 3, 4, 5]; num.push(6); console.log(num); For multiple values: var num = [1, 2, 3, 4, 5]; num.push(6, 7, 8, 9); console.log(num);

 How to add Elements to an Array Using the concat() method

The concat() method does not actually add elements to the existing array but rather creates a new modified array. This method is helpful when we need the first array in its original state. The concat() method can be used to add elements to both the beginning and end of the array: var num = [1, 2, 3, 4, 5];var num2 =[].concat(-5, -4, -3, -2, -1, 0, num); console.log(num2); To add elements to the end of the array: var num = [1, 2, 3, 4, 5];var num2 =[].concat(num, 6, 7, 8, 9); console.log(num2);

 How to add Elements to the middle of an Array using the splice() method

splice() is used to get rid of or insert elements in an array. This method is a bit different from the other methods which are discussed above. It requires three different arguments. The first argument defines where the item is going to be added in the array. The second parameter specifies the number of elements/items that are to be removed from the array. The second parameter will be zero in case of adding elements. The third parameter contains the values of the elements/items that are to be added. var num = [1, 2, 3, 4, 5]; num.splice(2, 0, 2.5); console.log(num);

 Conclusion

In this how-to guide we looked at four different ways of adding elements to an array. We can use the unshift() and the push() methods to add elements/items to the start and end of an array respectively. If we do not want to modify our original array but rather make a new array and add elements to it then we should use the concat() method. However, the splice() method gives us the most control over the index at which we want to add our new elements.

Break and Continue statements

Do you ever feel stuck at some point in life where you just want to get rid of a moment or an instance? When you just want to skip some moments and then go with the flow? That might not be possible in real life but it’s possible in programming languages like JavaScript by using break and continue statements. These statements are known as Loop Control Statements; We are going to explain the break as well as continue statements in this article. We will make sure that everything about both of the concepts is delivered properly and in a precise way.

 What is the Break Statement?

Commonly, we use break statements when we deal with the loop as well as switch statements. Let’s proceed through the working of the break statement in both statements.

 Working of break statement in a loop

How do you get out of a loop when you desire to do it whenever a specific condition occurs? That’s simple. The break statement is used at an instance whereby satisfying the condition being specified, the whole loop gets skipped and it takes you out of the loop. In other words, the loop is stopped. How to use break statement with the While loop In this example, we are going to notice and assess how the break statement works along with the while loop. The functionality of the break statement is going to be clear then: var k = 0; while (k < 6) { console.log("The number will be " + k) k++; if (k === 4) { break; } The condition is set to be less than 6 in the loop. The break statement will terminate the loop whenever the value of “k” gets equal to 4. That’s where we have applied the break statement. All the values up to 4 will be printed except 4 and above. Why? Because the loop will get terminated whenever the value of k will be equal to 4.

 How to use break statement with the For loop

In this aspect, we are gonna observe the functionality of the break statement in the for loop: for (i=1; i<=8; i++){ if (i === 5) break; console.log(i);} In the above scenario, as you can clearly see that the break statement is applied on the condition where the value is equal to 5. That means what? It clearly means that whenever the value is equal to 5, the loop will be stopped and all the values up to 5 except 5 will be printed.

 Working of break statement in switch

While dealing with the switch statements, we use break statements to exit the switch blocks. Whenever a break statement is encountered in a switch block, you jump out of the switch statement. In that case, the code after the break statement will definitely not work and it will also get skipped inside the switch block. The switch block, as a whole, will be ignored whatever code is thereafter the break statement. Now we will take a look at a couple of examples to better understand how break statement works:

 How to use break statement with JavaScript switch statement

The example we are going to encounter will indicate how the break statement works along with the switch statement: switch (new Date().getDay()) { case 0: console.log("Sunday"); break; case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; case 5: console.log("Friday"); break; case 6: console.log("Saturday");} In this case, whenever a single case is satisfied, it will break out of the switch block and will make sure that no further condition is checked or the code is run.

 What is the Continue Statement?

Let’s consider a situation where we are in a loop and we desire to break one iteration whenever a specified condition occurs and then we continue with the next iteration in the loop. The Continue statement is going to fulfill that desire for us. Unlike break, the continue statement “jumps over” to the next iteration/execution of the loop. Whenever a continue statement takes place, the loop condition is checked to see if the condition is satisfied or true and if so, it goes towards the next iteration.

 Working of continue statement in loops

For different types of loops, the behavior of the continue statement is different:

 Usage of continue statement While loop

We are going to deal with the while loop along with the continue statement. You will observe how the statement works. var i = 0; while (i < 6) { if (i === 2) { continue; i++; } console.log("The digit is " + i); i++;} In the above example, we have used a while loop together with the continue statement. The continue statement is applied just after the “if” statement in order to make sure that the iteration gets skipped whenever “i” gets equal to 2. Loop through the block of code where the value of “2” gets skipped. The output will be:

 How to use continue statement with the For loop

In this example, we will discuss the use of the continue statement in the JavaScript for loop. Let’s proceed. for (i = 1; i < 8; i++) { if (i === 3 || i === 4) continue; console.log(i);} In this example, we have used a for loop. In the “if” condition, we have specified that whenever the value is equal to 3 and 4, the iteration will be moved towards the next phase. That means that we are going to skip the iterations with the help of the continue statement whenever the value is equal to 3 and 4. The output will be:

 Conclusion

In this article, we have discussed everything related to the break and continue statements. We have learned to use the break statement to get out of a loop. We also learned how we can skip a single iteration in a loop whenever we desire to do so via the continue statement. From the description of the examples, we have achieved a precise level of understanding.

JavaScript Event Handlers

In JavaScript, an event is an action that occurs on a webpage inside the browser. This action can be typing in a field, clicking a button, or loading a page. The actions can either be initiated by the browser or the user; when any action occurs on a web page the browser notifies the system that an event has occurred. Developers can then respond to these events by writing functions that are known as event handlers.Event handlers are functions that listen for a specific type of event and when that event occurs they execute a block of code.

 What is Event Handling

An event is triggered any time a user interacts with a web page. This event can be anything from a user clicking somewhere on the page to loading a webpage. Whenever an event occurs on a web page the browser notifies the system; specific event handler functions listen for their respective events and when those events are triggered they execute the block of code written inside them. The code written inside the function contains all the actions that need to be performed in response to the event being fired. In this post, we will have a detailed discussion on different types of events and how to handle these events. Note: I will use the console to demonstrate the examples present in this post.

 What are the different types of events?

Some of the most common events that occur are: Mouse events: onclick mousedown mouseup mousemove Keyboard events: keydown keyup Form events: onfocus onblur Window events: onload onerror The list of all the events that occur is huge; we will only discuss the most common and widely used events.

 How to use click event

The onclick() event handler is used to listen to the click events on a webpage. Whenever the user clicks on an HTML element on a webpage, its respective onClick() event handler is triggered. Now Let’s look at an example to have a clear understanding of the click event handler: <!DOCTYPE html><html lang="en"><head><title>JavaScript Event Handlers</title></head><body><div class="buttons"><button onClick="clickEvent()" value="Button 1">Button 1</button><button onClick="clickEvent()" value="Button 2">Button 2</button></div><script> functionclickEvent(){ console.log(event.target.value + " is clicked"); }</script></body></html> We have a web page with two buttons i.e. Button 1 and Button 2: If we click on any of these buttons, their respective onclick() event handler is triggered which prints a message onto the console.

 How to use focus event

The onfocus() event gets triggered when an element gets or loses focus: For example, in the code snippet given below, the “focusEvent()” method is called on the onfocus() event in the input tag: HTML <h2> Type something here</h2> <input type="text" onfocus="focusEvent()" id="input1"/> JavaScript functionfocusEvent(){ document.getElementById("input1").style.background="green";}

 How to use KeyDown event

The onkeydown() event is triggered when a key is pressed by the user: For example, in the following code, the “keyDownEvent()” function is called on the “onkeydown” event, and the alert message is shown in the function definition: HTML <h2> Type something here</h2><input type="text" id="input1" onkeydown="keydownevent()"/> JavaScript function keydownevent(){ document.getElementById("input1"); alert("Pressed a key");}

 How to use load event

The onLoad() event is triggered right after the web page has been successfully loaded. For example, in the code snippet given below, a simple alert message is displayed on the onload() event in the body tag: <html><head>Javascript Events</head><body onload="window.alert('Page successfully loaded');"></body></html>

 Conclusion

Events are very important in making any web page interactive and responsive. An event can be initiated by the browser or the user. When a user interacts with the HTML elements of a webpage, an event is triggered. JavaScript gives us an option to respond to these triggers by using event handlers. In this how-to guide, we learned how to use event handlers to respond to events and make web pages more responsive.

Data Types? – Explained for Beginners

Every value is always distinct from each other, which categorizes them into various types. This categorization of various data is called Data Type. The reason for categorizing the data is to ensure how the data is being used within the program. Like any other programming language, JavaScript also consists of various data types. Data Type is dynamic, which means a single value can be stored in various ways. For example: let y; // Now y is undefined y = 10; // Now y is a Number y = "10"; // Now y is a String In this article, we’ll discuss various data types with examples.

 Types of Data

As discussed above, there are various data types, but all of them are categorized into three main categories:
    Primitive Type (String, Number, and Boolean) Composite or Reference Type (Object, Array, and Functions) Special Data Type (Null or Undefined)
Let’s discuss these types more thoroughly with examples.

 Primitive Type

Primitive data types are simple basic blocks of any language, having only one value assigned to them at a time. They consist of: Strings Numbers Boolean

 String Data Type

A sequence of characters enclosed by single or double quotation are represented through string data type. The string consists of numbers, names, and quotes, as long as they are within the quotation mark. Example let x = "16"; // number stored as a string var a = 'Hello World'; // using single quotation var b = "My Name is.."; // using double quotation var c = 'We\'re be very pleased.';// escaping single quote with backslash

 Number Data Type

Various types of numbers, such as negative or positive numbers with decimal places, and numbers with exponential notations are represented through this data type: Example: var a = 5; // integer var b = 25.5; // number with floating points var c = 1.25e+6; // exponential form, similar to 1.25e6 or 1250000 var d = 1.25e-6; // exponential form, similar to 0.00000125 Furthermore, number data types also represent special values like Infinity, -Infinity, and NaN. Infinity is produced by dividing a non-zero with 0, producing a number greater than all. Whereas, NaN shows “not a number”. This occurs through invalid or undefined mathematical operations. Example: console.log(10 / 0); // Output: Infinity console.log(-10 / 0); // Output: -Infinity console.log(10 / -0); // Output: -Infinity console.log("String" / 4); // Output: NaN console.log(Math.sqrt(-1)); // Output: NaN

 Boolean Data Type

Boolean data types represent the values of yes or no(on or off) through two specific values i.e true or false. Boolean values are used for various comparison purposes. Example var isEating = true; // yes, I'm eating var isHungry = false; // no, I'm not hungry.//comparison var a = 1, b = 3, c = 5; console.log(b > a) // Output: true console.log(b > c) // Output: false Output

 Composite or Reference

Composite Data type helps us to store various data types and complex entities as a collection. They consist of: Objects Arrays Functions

 Objects Data Type

Objects help in storing various types of data as a collection. A particular key name is given to the object, which is a string. This can store various data types like numbers, boolean values and strings as a collection. Example var anObjectUndefined = {}; var user = {"name": "Sam", "secondName": "Mathew", "age": "25"};// For better reading var book = { “bookName”: “Harry Potter and the deathly hallows”,"author": "J.K Rowling","genre": "Fiction","published": "2007","total copies": 10}

 Arrays Data Type

Arrays are used to store various values in a single variable. Arrays can be of various types, depending on the type of data stored. Each value within an array is indexed, starting from 0. This way a user can access each element through arr[0] or arr[2] etc. Example var fruits = ["Banana", "Orange", "Peach", "Pineapple"]; var languages = ["English", "French", "Persian"]; console.log(fruits[1]); // Output: Orange console.log(languages[2]); // Output: Persian Output

 Function Data Type

Functions are objects, with which a particular code is assigned. They are defined by using the keyword ‘function’ followed by a name given to them and parentheses enclosing parametric values. A function is then called and the lines it contains run and give an output. Example var greet = function(){return "Hello To the Universe!";}// type of the variable greet alert(typeof greet) // Output is a function alert(greet()); // Output is Hello To the Universe!

 Special Data Type

Special data type is:

 Undefined Data type

It contains only a single value. This happens when a variable is not assigned with any value, so at the time of interpretation, the output is displayed as ‘undefined’. Example var x; var y = "My Name is John" alert(x) // Output: undefined alert(y) // Output: My Name is John Here, the variable x was not assigned with any value. That’s why the interpreter showed the result as ‘undefined’.

 Null Data type

Similarly, the null data type also contains a single value. But, here in the case provided below, the value is assigned as “null”. So that it’s easily understood by the user that no value is assigned. Example var a = null;= alert(a); // Output will be null

 Conclusion

Data types are a major part of programming. It indicates which type of data the program is dealing with, whether it’s a number of various characters forming a string. In this topic, we explained various data types used and how they’re categorized. There are three main categories of data types and to store data specific types are present to store single as well as multiple data types. Each type is explained with examples for better understanding and implementation. This makes storing and manipulation of data easier for the user.

How to write Comments code

Comments are notes that a programmer leaves in their code to make it more understandable. Most senior devs focus on writing code which is efficient and can be easily read and interpreted by computers. However it is of equal importance to make the code easily readable for the people (who will be working with the code in future) as well. A programmer must know how to properly structure code to make it more understandable for humans.

 What are Comments?

Comments can be anything from a single line explanation to multi-line description of code that is written inside the source code of a program. They are usually used to leave notes in the complex parts of the source code so anyone who looks at the code in future can easily understand the purpose of that piece of code. This practice saves time as anyone can easily understand the purpose of code without making any effort. Now Let’s start learning how to properly structure JavaScript source code by writing different types of comments:

 Types of Comments

JavaScript has two main types of comments: Single-line comments. Multi-line comments Single-line Comments : In JavaScript two forward slashes (//) are used to write single-line comments: // A single-line Comment The comments in any programming language have no effect on the actual program. The interpreters/compilers of programming languages are designed in a way that they ignore all the comments when interpreting/compiling a program. Comments can have their own separate lines; they can also be added inline with other code as well. Inline Comments : When Single-line comments are used in the same line as code then they are referred to as inline comments: let a = 30; // an inline comment let b = a + 10; // adding 10 in "a" variable and assigning it to "b" The inline comments are used to explain the exact line of code they are written on; they can be used for a specific, small description of the code present at that line. Multi-line Comments : In JavaScript the block comments the multi-line comments are written in the same way as they are written in CSS with opening tags (/*) and closing tags (*/): /* A Block Comment*/ All the text between the opening and closing tags is ignored by the interpreters. Multi-line comments or Block-level comments are used to explain and give detailed description of a section of code. This type of comments are usually placed at the top of the source code file or before a particularly complex code block: /* Fetching the name of the user from an Input field and showing it on the console */ function showUser() {const name = document.getElementById('user-name'); console.log("Hello and welcome to the Linuxhint.com," + name + ".");} showUser(); Commenting Out Code for Testing/Debugging : Comments can be used to quickly and easily prevent the execution of a block code; so many senior JavaScript devs also use comments for testing and debugging purposes. Placing the comment tags behind a block of code so it is ignored by the interpreter and does not get executed is referred to as “commenting out code”. Commenting out code helps in pinpointing the cause of an error in code. They can also be used to test different blocks of code to get different results: // Function for dividing two numbers function division(dividend, divisor) { let quotient = dividend / divisor;return quotient;}// Function for subtracting two numbers function subtraction(num1, num2) { let sub = num1 - num2;return sub;}/* In the following line of code, we are commenting out the function call of the division function. Therefore, only the subtraction() function will be called and executed.*/// division(30, 5); multiplyTwoNumbers(9, 3);

 Practices for writing good JavaScript code

Here we will discuss the three best practices for writing good JavaScript code: Comments are generally written above the block of code they are explaining: // Show "Hello, Linuxhint!" on the console console.log("Hello, Linuxhint!");</td> Indent comments at the same level as the code immediately below them: // function definition function showUser() {// fetching the user-nameconst name = document.getElementById('user-name');// print the message on the console console.log("Hello and welcome to the Linuxhint.com," + name + ".");} Remember there is no way to end the inline comments; so they should be written only after the code for that line has been written completely: for (let i = 0; i === 10; i++) // for loop that runs ten times {// Running this code results in a syntax error}

 Conclusion

How many times have you solved a complex problem by writing some code only to come back a few months later and find out that you remember and understand nothing? Comments help you avoid that by writing detailed explanations/descriptions of your code. They also help in debugging testing and pinpointing the source of errors in your code. Both single and multiline comments can be used for debugging/testing purposes. If you are a beginner JavaScript dev, you should write as many comments as possible in your code as they are necessary to comprehend the code you write; but do remember that they should only be added where they are needed.

How to read and write text into a file using JavaScript?

In this article, we are going to talk about how to read or write text to a file. If you are a JavaScript developer you know that one cannot save a file locally as it can create massive security problems. Another method would be saving the file on our server. For this, we have to pass all the text data in our file to our server. After this, we have to use the server-related server-side language due to which we will be able to execute the written code in the file. Apart from this, we can also store the file on the client-side. An example would be using cookies to store the information. JavaScript does not hold the ability to access the user’s file system which is why we have to run the project on a server. To do this we will be using node.js which will aid us as we can use its built-in module or the library. We can use this to provide a download link of the text file for the users Prerequisite: How to import a library NodeJs provides us with a module or a library that handles everything related to write operations. It is known as “browserify-fs”. In simple words, we can say that “browserify-fs” is a JavaScript program where all the functions are written for writing operations. Let’s install browserify with the following command: > npm install browserify-fs When it is installed successfully, import the browserify-fs module in the required program. We can now use different functions to write texts or read texts from a file.

 Write to File

Let’s look at an example of a function that will create a new file with the specified name. If there already exists a file with that specific name then all of its data will be erased and rewritten. writeFile( Path_to_file, Data_to-be-written, Callback_function) The writeFile function is used for writing operations in Node; it accepts three different parameters as mentioned. Let’s look at them in a little depth: Path: It is basically the location or relative path to the text file where you want to create or rewrite a file. We can also just provide the name of a file and the file will be generated in the same folder as the program. Data: The data that is written to the file goes here. Callback Function: This parameter is very helpful as for example for some reason the operation did not write our data then it will generate an error and show us the error. It has an argument where we can pass the error string or the error argument.

 Demonstration of writing text into a file::

For writing text into the file, first, we have to require the “browserify-fs” module which includes the function definition of the writeFile() function. // Require browserify-fs which includes writefile() functionconst fs = require('browserify-fs') Later, let’s create a variable with the name of data in which we will have some string data to which we want to store into a file. // a simple text to write into the file let data = "Hello and Welcome to linuxhint.com" Now, access the writeFile function, provide it the file name along with the data you want to store into the file, and write an error handler callback function as shown below: // Writing data into the 'file.txt' file fs.writeFile('file.txt', data, (err) => {// error handling using throwif (err) throw err;}) After completing the code for writing some data into the file, the whole code snippet will look exactly like this: // Require browserify-fs which includes writefile() functionconst fs = require('browserify-fs')// a simple text to write into the file let data = "Hello and Welcome to linuxhint.com"// Writing data into the 'file.txt' file fs.writeFile('file.txt', data, (err) => {// error handling using throwif (err) throw err;}) Once all the code is written and when you will execute the above-given code, it will create a file in the browser. Now, let’s verify it by reading the same file.

 Read File

Now that we have written to a file, let’s read from a file. The function readFile() is used when we want to read the content of some file. Syntax: readFile( Path_to_file, Options, Callback_function) The readFile() function is used for reading operations; it also accepts three parameters as mentioned above. Let’s look at them in a little depth: path: Just like in writeFile(), the readFile() path parameter is also to specify the location of the file. Suppose we are and the program is in the same file then we have to just specify the file name and not the path we want to read. Options: An optional parameter/argument that specifies the data that is to be read from the text file. The default buffer is used, If no argument is passed. Callback Function: It is the function that further has two different arguments. These arguments are err and data. If the operation is not successful in extracting the data from the file then the err shows what the fault is, else if the operation is successful then the data argument has the data from the file.

 Demonstration of reading text from a file

We will use the recently created file file “file.txt”. file.txt data: “Hello and Welcome to linuxhint.com” For reading text from the file, first, we will require the “browserify-fs” module which includes the function definition of the readFile() function. // Require browserify-fs which includes readfile() functionconst fs = require('browserify-fs') Then, we will access the readFile() function, provide it the file name you want to read data from, and write a callback function for error handling and showing data: // Reading data from the 'file.txt' file fs.readFile('file.txt', (err, data) => {// error handling using throwif (err) throw err;// showing fetched data from the file onto the console console.log(data.toString());}) After completing the code for reading the data from the file, the whole code snippet will look exactly like this: // Require browserify-fs which includes readfile() functionconst fs = require('browserify-fs')// Reading data from the 'file.txt' file fs.readFile('file.txt', (err, data) => {// error handling using throwif (err) throw err;// showing fetched data from the file onto the console console.log(data.toString());}) Once all the code is written and when you will execute the above-given code, it will read the desired file from the browser and show all the data on the console, as shown in the screenshot given below: This is how you can read/write data into a file using the browserify-fs module.

 Conclusion

Writing or reading a file in any programming language is a necessity as we can develop small projects where we don’t need large databases. We then use file systems to read or write data to a file. In this article, we saw how to read or write text into a file. We used “browserify-fs” to achieve our task.

What are JavaScript Events

You are riding in a car and a signal comes, It’s red, You stop. When the signal turns green, you start driving again. Your actions were based on some signal provided to you. Same goes for events. When you are programming, you want some actions to be performed by clicking a button or pressing a key. The clicking of the button or the pressing of a key generates an event. Based on this event, some action is performed. For example, there is an article and a button that reads “show more”. When you click that button, the whole article becomes visible In this post, we are going to discuss everything about events with examples.

 What is an Event

To put it simply, an event is an action performed by a user or initiated by the browser. JavaScript responds/reacts to that action; this reacting/responding to the event is called Event Handling. Event handling is just a piece of code written by the developer. This piece of code runs when the event is triggered. Event handlers are also called event listeners. Events are fired within the browser window and are related or attached to a single or a set of elements. Events are of many different types. Some of them are: User presses a key on the keyboardUser hovers over an elementUser clicks an element via mouseUser closes the browserUser resizes the browserWeb Page is loading or has finished loadingWhen an error occursUser submits a form

 JavaScript Events

JavaScript provides us with a bunch of events. Listing all of them and explaining all of them under one article is impossible. Here I will only list the most common ones:

 Input Events

bluerchangefocuskeyup/keydownkeypress

 Mouse Events

MouseoverMouseoutMousedown/mouseup

 Click Events

clickDblclick

 Load Events

loadunloaderrorResize Now that we have discussed the theory, let us go to the practicality and discuss some real life examples of JavaScript events. Suppose I have a button and when I click that button, I want an alert to be shown to the user. The clicking of the button triggers the event and then a block of code will handle the event and react by showing an alert. <button class="clickme">Click Me</button> This is a simple button in an html file. Now we will get the button via the class name and then will handle the event i-e click. const btn=document.querySelector(".clickme"); btn.addEventListener('click',function(){ alert("You clicked the button");}); Put this code in a script tag or make another file with js extension and put it there. Now when we click the button an alert will be shown: There are also other ways we can implement this, for example: const btn=document.querySelector(".clickme"); btn.onclick= function(){ alert("You clicked the button");};

 Or:

const btn=document.querySelector(".clickme");function clickedMe(){ alert("You clicked the button");}; btn.onclick=clickedMe; The html file i-e the button remains the same. Note: You can put your JavaScript code in a script tag and then run your html file in the browser using live server or create a different file with js extension and reference it inside the header of the html file. Now let’s look at another example: Suppose we have a registration form. In the form we have two input fields and we want to put validation. If the user submits the form, we want to check whether the user filled both the inputs or left it empty. If both or one of them is empty we show an alert that the field is empty. Otherwise, we show an alert that says the user has registered: <body> <form id="myForm"> <input type="text" id="name" placeholder="Enter your name"> <input type="password" id="password" placeholder="Enter your Password"> <button>Register</button> </form></body><script>var myform = document.getElementById('myForm'); myform.onsubmit = function(){ const name=document.getElementById("name").value; const password=document.getElementById("password").value; if(name && password){ alert("Registered") } else{ alert("Fill the required fields please") }};</script> When we left the password field empty and clicked on the register an event triggered i-e submit. But based on our handler the input field “Password” was empty hence a message “Please fill the required fields” is shown. When we filled both the fields and clicked on the register button, “Registered” was shown.

 Conclusion

Events and event handling are really important concepts of JavaScript. When a user interacts with a web page an event is triggered. JavaScript provides event handlers to respond to these events and make web pages more interactive while providing immersive user experience. In those event handlers we can put our own code and logic and make something beautiful. In this post, we briefly discussed what JavaScript events are and how we can handle them; then we moved onto the types of events and event handlers and their real life applications.

What are Booleans

When we hear the word Boolean, two values come instantly in our minds: true and false. Boolean in programming language refers to logical data type. It represents yes/no, on/off through the words true and false. In JavaScript, boolean isn’t just a primitive type but also used in the form of an object. We all are already familiar with the primitive type of boolean, following is an example that shows two variables that are assigned with boolean values: let isHungry = false; let isSleeping = true; Now, if you apply the typeOf operator on these variables, it’ll give the result of boolean: console.log(typeof(isHungry)); // boolean console.log(typeof(isSleeping )); // boolean This is a simple boolean primitive type, but in this article, we’ll learn about the Boolean object with examples for your better understanding:

 Boolean Objects

In JavaScript, boolean can also be defined as objects using the keyword new and they’re then referred through capital B.

 Syntax

let y = new Boolean(variable/expression); Note: Variables with a value are always treated as true. Whereas, variables without any value or with “0”, “NaN”, empty string, “null” are always treated as false boolean values.

 For example

Boolean for a value is always true console.log('Boolean(30) is ' + Boolean(30)); console.log('Boolean("Hello World") is ' + Boolean("Hello World")); console.log('Boolean("false") is ' + Boolean("false"));

 Output

Boolean for no defined value console.log('Boolean(0) is ' + Boolean(0)); console.log('Boolean(NaN) is ' + Boolean(NaN)); console.log('Boolean(null) is ' + Boolean(null));

 Output

The Boolean object is an object wrapper for a boolean primitive type. A boolean object is created when the user passes either true or false values into the constructor.

 Example

let a = new Boolean(false); Now, to return the primitive value just call valueOf() method on the Boolean object: console.log(a.valueOf()); // false Moreover, if we apply same typeOf() method on Boolean object it return object instead of boolean: let a = new Boolean(false); console.log(typeof(a)); // object is returned

 Boolean Properties

PropertyDescription
ConstructorBoolean() Returns the reference of the boolean function that created that object.
PrototypeThis static property returns the reference to the Boolean prototype object. It allows adding any predefined properties to the boolean object.

 Boolean Methods

NameDescription
valueOf()A primitive value is returned of the Boolean object.
toString()A string of either true or false is returned that represents the current value of the Boolean object.
toSource()Source code is returned as a String, of the current Boolean object.

 Example

//toString method var obj = new Boolean(false); console.log(obj.toString()); var obj = new Boolean(true); console.log(obj.toString()); //valueOf method const x = new Boolean(); console.log(x.valueOf()); const y = new Boolean('Hello World'); console.log(y.valueOf());

 Output

Furthermore, a Boolean object always returns true in a conditional statement regardless of whatever value is assigned to it.

 Example

let obj1 = new Boolean(false);// using it in the if conditionif(obj1){ document.write("It is a boolean object"); // executes}// Following is a primitive value let obj2 = false;if(obj2){ document.write("It is a primitive type of boolean"); // it’ll not be executed}

 Output:

In the above example, Boolean objects and primitive types of boolean are compared. Despite the fact that a false value was assigned to a Boolean object, it was still executed. The reason is that the object evaluates to true when it’s provided in an if condition.

 Conclusion

Boolean refers to two values in programming, but, they’re not just used as primitive data types but also in the form of objects. In this article we learned what Booleans are, how primitive and object types of booleans differ. Boolean objects have some properties and methods. Through example, we demonstrated how to assign false and true values and how Boolean objects behave in a conditional statement.

Top 5 JavaScript Code validators

JavaScript has been on the ascent and is one of the most widely used languages in order to design interactive websites. It is used in frontend/client-side as well as backend/server-side development. JavaScript makes web pages more dynamic and interactive.

 What are validators?

In simpler words, validators are computer programs used to check the validity and accuracy of parts of a code or document. In other words, code validation checks if the encoding of a web page complies with the standards and recommendations established by the World Wide Web Consortium (W3C) for the network.

 Top 5 JavaScript Code Validators

As discussed above, JavaScript validators are used to test code and find errors. Regardless of your level of writing code experience, you will have to use a code validator to either authenticate/validate or debug your code sooner or later. Even if you’re a JavaScript pro, there is no harm in validating your code to make sure everything is good to go. If you are searching for new facilities to validate your code, then you have come to the right place; this article will provide a thorough analysis of the top 5 JavaScript code validators. These validations will help you seek out every little bug in your code:

 JSHint

On top of the list, JSHint takes the place because of its great features, user-friendliness and compatibility with any environment. The tool is written which helps to identify and report typical mistakes and possible bugs. JShint is an open source platform and can be easily adjusted in the environment where your code is expected to run. You can simply use it by entering the code in the left section of the page. Once the code has been validated, you’ll see the report on the right side. Main Features Community driven tool Flexible Publically available

 Esprima

There is always a tough competition to be at the top place and Esprima is not far behind. Esprima does not check for common problems in the code but rather checks for syntactical errors. Esprima is perfect for when you forget to put a semicolon or square brackets somewhere and want to quickly find a solution. Main Features Supports syntax tree format Support for JSX, a syntax extension for React Heavily tested

 Code Beautify

This code validator tool is basically a JS checker that detects errors and collects information about the total length of the code including the total number of words and the total lines. Code Beautify is a great tool to use to quickly and easily check your JavaScript or jQuery code. Main Features Support JSX syntax Beautify/format your JavaScript Helps to obfuscator(change variable name and minify) and packers Beautify JS works on Chrome, Firefox, Edge, and Safari etc.

 JSLint

JSLint is a tool for code supervision and for error detection, another important aspect of programming. JSLint is one of the most flexible and customizable code checker for JavaScript that allows you to choose from several options. These options define how your code is validated; By choosing a few things you want to “allow” the checker, you can avoid making unnecessary errors about things you already know, or don’t plan to fix. Also, you can choose options for CouchDB or Node.js. In simpler words you can say that analyzing potential flaws in your code is called “linting” and thus as the name suggests it is one of the most widely used Linting JS tools.

HTML Code Sniffer

HTML Code Sniffer is used for validating HTML source code and the JavaScript code embedded inside HTML. It looks for any violations of the defined coding standard; it is written so it can work without communicating with the server. The developers can create their own “sniffs” to enforce their own coding standards.

 Conclusion

Code validators look for errors in code; most modern IDEs and code editors come fully equipped with code validators. This article lists the top 5 JavaScript code validators which will come in handy if you do not have access to a code editor that has an inbuilt code validator. It is important to consider the main features of each code validator tool and choose the one that best suits your needs.

JavaScript Variables – What is the difference between var, let, and const?

In ECMAScript 2016, JavaScript introduced two new methods to declare variables with let and const keywords. JavaScript only had one option to declare variables before 2016 i.e. the var keyword. In this article we will learn why there are three different ways to declare variables; we will also cover the difference between these three articles. Additionally, this article will also introduce you to concepts such as variable scope and hoisting. So let’s get started by understanding what is variable scope:

 What is Scope

In JavaScript, the scope is defined by curly brackets. It defines a block of code that needs to be executed together. JavaScript has two kinds of scopes: Function-scope Block-scope Function-scope : Any variable created inside a function using var is function-scoped. Its visibility is restricted to the definition of the function and it cannot be accessed from anywhere outside the function: function showMessage() { var message = 'Hi from Linuxhint'; console.log("in: " + message); // 'Hi, Linuxhint!'} showMessage(); console.log("out: " + message); ReferenceError: message is not defined Block-scope : A block of code is defined by curly braces. This type of scope will help us prominently differentiate between the three methods of declaring variables: Following is an example where we have declared variables with var, let, and const in an if block and then logged them to the console: if (true) { var message1 = 'Hi from Linuxhint'; let message2 = 'Hello from Linuxhint'; const message3 = 'Hi again from Linuxhint'; console.log("in: " + message1); // 'Hi from Linuxhint'; console.log("in: " + message2); // 'Hello from Linuxhint'; console.log("in: " + message3); // 'Hi again from Linuxhint';} All of the variables have been logged to the console without any error as they were logged from the same block. However, if we try to log them from outside of the if block, the below-mentioned error will appear: if (true) { var message1 = 'Hi from Linuxhint'; let message2 = 'Hello from Linuxhint'; const message3 = 'Hi again from Linuxhint'; console.log("in: " + message1); // 'Hi from Linuxhint'; console.log("in: " + message2); // 'Hello from Linuxhint'; console.log("in: " + message3); // 'Hi again from Linuxhint';} console.log("out: " + message1); // 'Hi from Linuxhint'; console.log("out: " + message2); // ReferenceError: message2 is not defined console.log("out: " + message3); // ReferenceError: message3 is not defined

 How to use var to declare a variable

Before ECMAScript 2016 var was the only method of declaring a variable but it had several issues associated with it, so new methods were introduced which could be used to declare variables. We will first understand var and then we’ll talk about these issues: Scope of var : Variable scope basically means where the variable will be available to use. Variables that are declared with the var keyword either have global or local scope. Variables that are declared outside function block using var have global scope. Global scope means that a variable is available to use anywhere in the window. When the variable is declared inside a function it is function-scoped which means that it can only be used inside the function: To understand further, look at the example below: function showMessage() { var message = 'Hi from Linuxhint';} Here, the message is function scoped so it cannot be accessed outside of the function. So if we do this: function showMessage() { var message = 'Hi from Linuxhint';} console.log("out: " + message); // ReferenceError: message is not defined This will give us an error which is because the message is not available outside the function. var outside of a for-loop : The variable “i” can be accessed from the outside of the for-loop. for (var i = 0; i < 5; i++) { console.log("in: " + i);} console.log("out: " + i); var variables can be re-declared and updated : In JavaScript variables declared with var keyword can be redeclared and updated in the same scope: function showMessage() { var message = 'Hi from Linuxhint'; message = 'Hello from Linuxhint'; var message = 'Hi again from Linuxhint'; console.log(message); // 'Hi again from Linuxhint';} showMessage() How to use let to declare a variable : The let keyword is now preferred over var for variable declarations; it comes with a few improvements over var. let is block scoped : In JavaScript, a block of code is the collection of statements that are bounded by a pair of curly brackets {}. A variable declared using the let keyword is only available to use within that block and cannot be accessed from outside: if (true) { let message = 'Hi from Linuxhint'; console.log("in: " + message); // "Hi from Linuxhint"} console.log("out: " + message); // ReferenceError If we use the message outside of the block where it was defined, it will return an error. This is because let variables are block-scoped. let outside of a for-loop : The following example demonstrating the let variable output using for loop: for (let i = 0; i < 5; i++) { console.log("in: " + i);} console.log("out: " + i); let can be updated but not re-declared : A variable declared with let can be updated within its scope just like var, but unlike var, it cannot be redeclared: let message = 'Hi from Linuxhint'; message = 'Hello from Linuxhint'; The console is completely empty and is not returning any errors. These statements will return an error: let message = 'Hi from Linuxhint'; let message = 'Hello from Linuxhint'; // SyntaxError: Identifier 'message' has already been declared However, redefining the same variable in a different scope using let does not return any error: let message = 'Hi from Linuxhint';if (true) { let message = 'Hello from Linuxhint'; console.log("in: " + message); // "Hello from Linuxhint"} console.log("out: " + message); // "Hi from Linuxhint" The let keyword treats these two variables as different if they are in different scopes so it does not return any error; this feature of the let keyword makes it a better choice than var. When using let, you can reuse variable names in different scopes without worrying about whether you have used that variable name before.

 How to use const to declare the variable

The variables declared using the const keyword have constant values. This means that their values cannot be changed/reassigned. Similar to the variables declared with the let keyword, the variables declared with the var keyword are also block-scoped. const can’t be re-declared or reassigned : The variables declared with the keyword const cannot be redeclared or reassigned within the same scope. So if we have declared a variable with const keyword, we cannot do this: const message = 'Hi from Linuxhint'; message = 'Hello from Linuxhint'; // TypeError Nor will we be able to do this: const message = 'Hi from Linuxhint';const message = 'Hello from Linuxhint'; // SyntaxError Every variable which is declared using the const keyword must be initialized at the time of its declaration. This behavior of the const keyword somehow changes when it comes to objects. While the object declared cannot be updated, its properties can be changed So, if we declare an object with const: const user = { name: "Steve", age: 13} While this cannot be done: user = { userName: "Harry", grade: "3rd"} // TypeError: Assignment to constant variable. This can be done: user.name = "Harry"; This will change the value of the user.name without returning any errors.

 Final review

Variable Declaration Function-scope Block-scope Redefinable
var
let
const

 Conclusion

It is generally a good practice to avoid using var to declare variables because the function scope is confusing and is not as obvious as the block scope. The let and const keywords encourage devs to use better coding practices. You should generally use let for the variables that you’ll need to reassign and use the const keyword for all other variables. This article thoroughly explains all three variable types with examples.

How to round decimal numbers

Rounding off is a very common operation when working with numbers. JavaScript provides a Math object that can be used to round decimal numbers. The Math object provides several different methods which can be used to convert decimal numbers into whole numbers. JavaScript also has another method .toFixed() which can also be used to round a decimal number upto or down to certain decimal places.

 How to round a decimal number

First we will discuss all the methods provided by the Math object for rounding off a decimal number: Note: We will use the browser console to demonstrate examples performed in this post. Math.ceil() method : The Math.ceil() method rounds the decimal number upto its nearest integer: If we give a negative number as an argument then: Math.floor() method : This method rounds the decimal number down to its nearest integer: For a negative number: Math.round() method : The Math.round() method takes a number as an argument and returns its nearest integer. It rounds the number down to the nearest integer if the digit after the decimal is less than 5: If the number after the decimal is greater than five then this method rounds the number up to the nearest integer: If the number after the decimal is 5 then the Math.round() method rounds the number to its nearest integer in the direction of +infinity: Math.trunc() method : This method truncates the decimal part of a number number and only returns the whole number part: For negative numbers: How to use the .toFixed() method : The .toFixed() method is used to round a decimal number upto or down to a specific number of decimals. It takes one optional argument which specifies the number of decimals which by default is 0: If we want the number to have 2 decimal points then: If the specified number of decimal points is higher than the decimal points present in the number then 0s are added to create the desired length: This method converts the number into a string:

 Conclusion

Rounding and truncating decimal numbers is a very common problem that every developer has to face. In this post we have listed the five most common solutions present for rounding off or truncating decimal numbers. The Math.ceil() method rounds the decimal number towards its nearest integer in the direction of +∞ whereas the Math.floor() method rounds the number in the direction of -∞. The Math.round() method rounds the decimal numbers in both directions depending upon the digit that comes after the decimal point. The Math.trunc() method truncates all the digits after the decimal point and returns just the whole number part of the decimal number. The .toFixed() method is used to get the desired number of digits in a decimal number every time.

What is the addEventListener method.

, an event is an action that occurs on a webpage. This action can be anything from clicking of a button to loading of the page. Several events can occur simultaneously and can be initiated by either the user or the browser. To manage these events, event handlers are required. When an event occurs inside a browser it alerts the system which can then handle (respond to) these events. In this post we will have a detailed discussion on the AddEventListener() method and how we can use it to capture and handle events.

 What is AddEventListener()

JavaScript provides us with the addEventListener() method, which is an inbuilt function which can be used to specify a function which will be executed in case a particular event is triggered. Syntax target_element.addEventListener(event, function, useCapture) target_element: This is the HTML element to which we want to attach the event handler. Parameters are: event: It’s a valid JavaScript event that is written without the ‘on’ prefix. For example, ‘click’ is written instead of ‘onClick’. The function executes once this event occurs. function: This function is a listener that is executed in response to a triggered event. useCapture: It’s an optional Boolean value which decides which event type to use (event bubbling or event capturing).

 What are Event Bubbling and Event Capturing

The third optional Boolean parameter, useCapture, determines the event propagation, which decides the sequence of occurrence of an event. If there’s <p> element inside a <div> element and the user clicks on the <p> element, which of the event of click should occur first? In bubbling, which is represented by false, the sequence of occurrence goes from inner to outer. The <p> tag will be handled first and then the <div> tag. Whereas, for capturing, that’s represented through true, the outermost event is handled first before the inner element. First, <div> will be handled and then the <p> tag.

 Example

Here, two parameters are passed. By clicking the button the function is called that displays the text: <body> <button id="try">Click here</button> <h1 id="text"></h1> <script> document.getElementById("try").addEventListener("click", function(){ document.getElementById("text").innerText = "Welcome Back"; }); </script> </body>

 Conclusion

The addEventListener method allows you to capture events and then execute the specified function based on the event that has occurred. It takes three parameters; one of which is optional. The third (optional) parameter, useCapture, is a Boolean parameter that decides the sequence of the events that is occurring. In this post we have had a comprehensive discussion on what is the addEventListener() method and how to effectively use it in our JavaScript code.

Top 5 popular games built on JavaScript

Almost every computer fanatic must have once thought in his life to develop games. Afterall, games are one of the best means of entertainment. As JavaScript has gained so much popularity the question arises; whether JavaScript can be used to develop games or not? The answer is yes ! There was a time when a simple game developed would require an Adobe flash player. JavaScript has come a long way. Nowadays, people can play games developed on any browser and at any platform without the need for a flash player. Developers mainly use HTML5 and WebGL to achieve this. These technologies also reduce the size and make it more attractive; In this post we are going to discuss the top 5 such games that are developed.

 HexGL

This is a very addictive fast racing game. In this game, there is a spaceship, and you control it by using your keyboard or touchscreen device. This is an open-source game which was designed in HTML5 and JavaScript. What makes this game very good is its amazing UI design which catches one’s attention and makes them feel like they are inside a spaceship flying in space. Play Now

 Super chrono Portal Maker

This game is just like the retro super Mario game. They say men never grow when it comes to gaming, I would like to agree. Having levels up to 30 and making super Mario run and jump makes this game very interesting. Each level has its own difficulty and a new twist so you won’t get bored while playing this game. This game has another cool feature which is the level builder. One can create levels in this feature and then share with our friends. Play Now

 2048

This is an online game where you use your keyboard arrows to move tiles and merge them. By merging, you have to make the desired number, usually the number is 2048; Most people would have already played a version of this game. It is available in the play store by the name of 1024. This game looks simple, but isn’t. This is the reason why this game is so addictive. Play Now

 Gods will be watching

Another very cool game developed. You will have to survive for 40 days in complete isolation with 6 other characters in this game. Sounds creepy? Yes, maybe this is the reason why it is so popular and among my top 5 JavaScript games. There are also 6 other characters. Some of them are a robot, a dog and a psychiatrist. You need to cooperate and collaborate with these characters and survive. You also need to find ways and methods to keep them well fed, warm and sane. Play Now

 Mimstris

If you have some free time, this is the game you are going to enjoy the most. You probably have already played the retro Tetris game. This is exactly like that but built using react and redux JavaScript. An online puzzle game in which one has to arrange the blocks consisting of different shapes appearing randomly and by placing those blocks as a horizontal line just like in the Tetris game. Play Now

 Conclusion

With JavaScript gaining so much popularity, numerous developers have started developing games in this language. Another reason for this shift is the ending of the compulsory adobe flash player. Nowadays, one can make amazing, stunning games with cool UI designs using JavaScript. If you play some of the games we mentioned in this article, I am sure it will motivate you to start developing games.

JavaScript query selector() method – Explained

JavaScript is mainly used to add interactive and dynamic content to static HTML pages, but to add such content it needs to access the HTML elements which are present in the DOM (Document Object Model). JavaScript offers several different methods to access the HTML elements present in the document. Here we will discuss in detail, what is the querySelector() method and how to use it:

 What is querySelector() method

Do you want to search for and access any element within the document? The querySelector() is the perfect method you have got for the proposed functionality. The querySelector() is a method that plays a major role in searching for elements. It is a method from the DOM API that allows us to get or retrieve a single element that matches the parameter being passed. The querySelector() returns null if no matches are found; However, if there are two matches in the document, it will access only the first occurrence. Now we will discuss the syntax of the querySelector() method before moving onto the examples to better understand the querySelector() method.

 Syntax

element = document.querySelector(selector(s)); The querySelector() method takes only one parameter which specifies one or more selectors; These selectors are used to select the first HTML element based on its type, attribute, or the value of its attribute, etc. Here we will use different CSS selectors to properly show how the querySelector() method actually works: The Universal Selector The asterisk sign (*) is known as the universal selector; it is used to access all the elements of the document: <h1>Hello!</h1><p>Welcome to Linux Hint!</p><script> document.querySelector("*").style.color = 'red';</script>

 The type/tag selector

We can search for any element by passing the value of its tag to the querySelector() method. For example, if we want to get the “<p>” tag from the HTML DOM and change its color to red, the code will go like this: HTML <h1>Hello!</h1> <p>Welcome to Linux Hint!</p> JavaScript <script> document.querySelector("p").style.color = 'red';</script>

 The ID selector

The # sign is used to select an element based on its ID; IDs are supposed to be unique and no two elements on a single HTML page should have the same ID: For example, to change the color of an HTML element whose ID is “example-id”, the code will look like this: HTML <h1 id="example-id">Hello!</h1><p>Welcome to Linux Hint!</p> JavaScript <script> document.querySelector("#example-id").style.color = 'red';</script>

 The Class Selector

The dot “.” sign is the selector for the class attribute which is used to select an element based on its class. Multiple elements can have the same class but the querySelector() method will only return the first element: For example, to change the background color of an HTML element whose class is “example-class”, the code will look like this: HTML <h1>Hello!</h1><p class="example-class">Welcome to Linux Hint!</p> JavaScript <script> document.querySelector(".example-class").style.backgroundColor = 'red';</script>

 Multiple selectors

We can give a combination of multiple selectors the querySelector() method as well, these selectors should be separated by commas. However, it will only access a single element whichever occurs first in the HTML code sequence: For example, if we mention two HTML tags in the querySelector() method: <script> document.querySelector("h2, p").style.backgroundColor = 'red';</script> While our HTML tags are placed in the following sequence <h1>Hello!</h1><p>Welcome to Linux Hint!</p><h2>JavaScript querySelector() method - Explained</h2> The querySelector() method will only return the first match which is <p> tag: To access multiple elements, the querySelectorAll() method is used:

 querySelectorAll() Method

Suppose, we want to change the color of all the <p> tags whose class is “green”. The HTML and JavaScript will go like this: HTML <p class="green">Welcome to Linux Hint!</p> <p>Welcome to Linux Hint!</p> <p class="green">Welcome to Linux Hint!</p> <p class="green">Welcome to Linux Hint!</p> <p>Welcome to Linux Hint!</p> JavaScript <script> var greenPara = document.querySelectorAll(".green"); for (let i = 0; i < greenPara.length; i++) { greenPara[i].style.backgroundColor = "green"; }</script>

 Conclusion

The queryselector() method is an efficient way to access HTML elements in DOM. JavaScript provides other methods for accessing DOM elements as well but queryselector() is the most versatile and offers the most options when it comes to DOM manipulation. From the introduction to the examples, this post has explained and clarified almost every aspect precisely and thoroughly. With the help of examples, it has clearly described the concept of the queryselector() method.

JavaScript Object.keys(), Object.values() and Object.entries() methods – Explained

Objects are a data type which is used to store data in the form of key: value pairs; Working with this data can become a tedious task because objects themselves are not iterable. So we just translate them into arrays which are iterable objects. The Object.keys, .values and .entries methods are built-in JavaScript methods that help us convert objects into arrays so we can work with data stored in objects in an efficient manner. These three methods take objects as parameters and return an array consisting of strings. If the argument is an array, it will be treated as an object. They iterate over the keys/values (or both) of the object one by one just like a loop In this guide we will comprehensively discuss the Object.keys, .values() and .entries() methods; So let’s get started with the Object.keys method:

 How to access object keys

The Object.keys() method is used to access the keys (properties) of an object by passing the object to it as a parameter. It will return all of its keys as strings in an array. Now we will take a look at the syntax and an example of the Object.keys method to better understand how it works:

 Syntax

Object.keys(myObject); The myObject is the object whose enumerable property names we want. Now let’s look at an example: const user = {firstName:"Mary", lastName:"Jane", age:23, id:01}; console.log(Object.keys(user));

 How to access object values

The Object.values() method is used to access the values of an object by passing the object to it as a parameter. It will return all of the values of its properties as strings in an array. The syntax of the Object.values() method is same as the Object.keys() method, just replace .keys with .values: Object.values(myObject); Now, let’s look at an example: const user = {firstName:"Mary", lastName:"Jane", age:23, id:01}; console.log(Object.values(user));

 How to access each object entry

The Object.entries() method is used to access the keys (properties) of an object and their values by passing the object to it as a parameter. It will return all of its keys and their values as strings in an array. Its syntax is just like the previous two methods: Object.entries(myObject); Following is the example of the Object.entries() method: const user = {firstName:"Mary", lastName:"Jane", age:23, id:01}; console.log(Object.entries(user)); We can access any entry using the array index: const user = {firstName:"Mary", lastName:"Jane", age:23, id:01}; console.log(Object.entries(user)[0]); If we want to access the key or its value inside the array then we will need to provide two indices: const user = {firstName:"Mary", lastName:"Jane", age:23, id:01}; console.log(Object.entries(user)[0][1]);

 Conclusion

Until very recently JavaScript lacked the tools needed for reading and manipulating keys of objects and their values. But in recent versions JavaScript has provided some standard methods for accessing the entries of an object. The Object.keys, .values and .entries are three such methods which are used to extract data from JavaScript objects for further processing. In this how-to guide we learned to use the Object.keys, .values and .entries methods.

What is Math Object

JavaScript has an object called the Math Object which provides methods and properties that can be used to perform different mathematical operations code. Math is a built-in object like the Date object; but unlike the Date object it is not a constructor and has static properties; You do not need to create the Math object to use its properties and methods. The Math object has many different objects and properties; some of which will be talked about in this post. First of all we will discuss the properties of the Math object Note: The browser console is used for the demonstration of examples in this article.

 The properties of the Math Object

The Math object has eight different properties all of which return a constant. The .PI property is used to get the value of PI code: var pi = Math.PI; console.log(pi); The list of other seven properties is given below: E SQRT2 SQRT1_2 LN2 LN10 LOG2E LOG10E Math.E : This property is used to get the Euler’s number: var e = Math.E; console.log(e); Math.SQRT2 : This property returns the value of the square root of 2: var s = Math.SQRT2; console.log(s); Math.SQRT1_2 : The Math.SQRT1_2 is used to get the value of the square root of half (): var s = Math.SQRT1_2; console.log(s); Math.LN2 : When we need the value of the natural log of two in our code then we use the Math.LN2 property: var l = Math.LN2; console.log(l); Math.LN10 : We can get the value of the natural log of ten in the following way: var l = Math.LN10; console.log(l); Math.LOG2E : This method returns the base 2 logarithm of E: var l = Math.LOG2E; console.log(l); Math.LOG10E : Similar to the Math.LOG2E property this property also returns the value of the logarithm of E but of base 10: var l = Math.LOG10E; console.log(l);

 The methods of the Math Object

The Math object offers many methods; the most common of which will be discussed here:

 How to use the Math.round() method

The Math.round() method is used to round a number to its nearest integer: var num = Math.round(1.4); console.log(num); And if the digit after the decimal is 5 or greater than five then: var num = Math.round(1.5); console.log(num); Similarly, the Math.ceil() and the Math.floor() methods are used to round the number up to its nearest integer and down to its nearest integer respectively. Two other methods Math.trunc() and Math.sign() were added in the ES6 version. Math.truc() function truncates the decimal part of an integer and returns the whole number whereas Math.sign() returns 1 or -1 to show whether the integer given to it was negative or positive. It returns 0 if you give it 0 as an argument:

 How to use the Math.pow() and Math.sqrt() methods

The Math.pow() method takes two different numbers as arguments and returns the value of the first argument as the power of the second: var num = Math.pow(2, 8); console.log(num); The .sqrt() method takes a single argument and returns the value of its square root: var num = Math.sqrt(256); console.log(num);

 Conclusion

In JavaScript the Math Object provides different properties and methods to quickly perform a lot of mathematical operations. Some of these methods and properties were discussed in this article; these properties and methods are quite useful and commonly used programs. The Math object also provides a ton of other handy methods as well such as the sin(), cos(), tan(), log(), and min(), max() etc.

JavaScript While Loop – Explained

In computer programming, loops are used to iterate (repeatedly execute) through a block of code until a specific condition is fulfilled. Most major programming languages include multiple types of loops, for example, for and the while loop. These loops are syntactically different but are essentially used for the same purposes meaning they can be replaced with each other in most cases. This write-up will be focussing on the while loop:

 How to use while loops

We will first discuss the syntax of while loop: while (condition) { // Statement} The while loop statement takes a single argument which is the condition for the termination of the loop. The loop will keep on iterating until this condition becomes false. Now we will discuss a few examples to better understand while loops. Note: The browser console is used for the demonstration of examples in this article. For our first example we’ll look at a program which prints the table of a number to the console. If we do not use any loops then the program will look like this: console.log("2 * 1 = " + 2 * 1); console.log("2 * 2 = " + 2 * 2); console.log("2 * 3 = " + 2 * 3); console.log("2 * 4 = " + 2 * 4); console.log("2 * 5 = " + 2 * 5); console.log("2 * 6 = " + 2 * 6); console.log("2 * 7 = " + 2 * 7); console.log("2 * 8 = " + 2 * 8); console.log("2 * 9 = " + 2 * 9); console.log("2 * 10 = " + 2 * 10); The code in the above example looks repetitive; we can perform the same task in a few lines of code using a loop; Here we will use the while loop: i = 1; while (i<=10) { console.log("2 * " + i + " = " + 2 * i) i++;} As already mentioned above loops are interchangeable; they can be replaced with each other. The task performed in the example given above can be performed by using a for loop. In general for loops are used when the loop has to run for a definite number of times whereas the while loop is used when the loop is going to run for an indefinite number of times until the condition is satisfied. For our next example we will create a program with a while loop which will run for an indefinite number of times: randomNumber = 0; while (randomNumber < 500) { randomNumber = Math.trunc(Math.random()*1000); console.log(randomNumber);} In the example given above we first created a variable named randomNumber and assigned it a value 0. This was only done because the while loops check the condition before every iteration (on the first iteration the loop ran because the condition was true as 0 < 500). We then declared a while loop and gave it a condition which is randomNumber < 500. Inside the body of the loop we used the Math object to get a random number between 0 and 999 and assigned this number to the randomNumber variable. Then we used the console.log method to print the randomNumber onto the console. The while loop kept iterating and the Math object kept generating random numbers until the condition was met which was a random number greater than 500.

 How to use break statement with while loop

JavaScript gives us the option to use break statements inside the body of the while loops to terminate the loop. The break statements can be combined with other statements such as the conditional if statements to terminate the loop from inside its body once a specific condition is met. For our next example we will take the code from our first example and modify it so the loop breaks if there is a multiple of ten inside the table of 2. i = 1; while (i<=10) { if ((2 * i) % 10 == 0) { break; } console.log("2 * " + i + " = " + 2 * i) i++;} As 10 satisfies the condition of our break statement the loop is executed after the fourth iteration.

 How to use continue statement with while loop

The continue statement skips the current iteration of the loop upon satisfying the condition and moves to the next instead of terminating the loop: i = 1; while (i<=10) { if ((2 * i) % 10 == 0) { i++; continue; } console.log("2 * " + i + " = " + 2 * i) i++;} If there is a multiple of 10 in the table of 2 then the continue statement skips the iteration and moves to the next:

 What is do while loop

The do while loop is built on top of the while loop meaning it is an extension of the while loop. The while loop checks the condition before execution of the loop’s body. The do while loop evaluates the condition after the execution of the loop’s body. So the code written inside the do section will always run at least once: var number = 10;do { console.log("The do while loop is running");} while (number < 5); In the example above the code in the body of the do while loop was executed for the first iteration even though the condition was false.

 Conclusion

Loops are one of the most powerful tools in any programming language used to iterate over blocks of code. In this article we have learned about the while loop which is a type of loop present and many other programming languages; moreover we also learned to combine the while loop with some other statements to make it more powerful.

What are the top 5 best JavaScript Game Engines

JavaScript is a cross platform scripting language used for both front and back end; Although major game development companies are not using JavaScript to develop their games, the idea of Game Development is not absurd. In recent years browsers have become a lot more powerful and with technologies like WebGL becoming increasingly popular, it has become a lot easier to render 2D and 3D graphics in browsers which makes for great user experience. The greatest thing about games which are browser-based is the platform independence. They can run across multiple platforms such as iOS, Android, Windows or any other platform There are plenty of JavaScript resources out there that may be utilized for creating browser based 3D games utilizing HTML5 and WebGL. However, choosing the proper game engine can be a problem if you’re new to creating games using JavaScript. We will help you eliminate this problem by providing a list of the top five JavaScript game engines.

Babylon.JS

Babylon.JS is a rendering engine which can be used for game development. You will first need to create the engine, only then you can start game development if you use Babylon.JS for your project. This gives you greater control over your project. Some of the main features of Babylon.JS framework are cameras, meshes, scene graphs with lights, materials and physics engine, collision engine, audio engine and optimization engine. Babylon.JS has a great tool called playground as well which can be used to test your projects. You can download the source code for free from Babylon’s GitHub repository.

PlayCanvas

PlayCanvas is an open source, industrial grade, JavaScript based game Engine that has lots of tools for developers which enable you to create 3D games in no time. PlayCanvas.js was not open source originally but now you can clone it on GitHub and use it for your next gaming project. PlayCanvas has a cloud based editor, so getting started is very easy. So starting a new project on PlayCanvas is as simple as going to the Editor URL on your browser. You can use this editor to set things up, write code and test it out. The editor also enables cooperation across teams which basically implies several individuals may work on the same project simultaneously. PlayCanvas.js is supported by the tech giants like Mozilla, Activision and ARM. You can get the source code from here.

Three.JS

Three.JS is another complete and powerful JavaScript 3D framework for performing anything 3D, ranging from making basic 3D animations to building interactive 3D games. Three.JS library supports a lot more features than simply supporting WebGL renderers, it comes bundled with SVG, CSS3D renderers and Canvas as well. However, from a gaming viewpoint you may want to concentrate only on the WebGL renderer of the Three.JS library. The source code of Three.JS 3D engine can be downloaded from GitHub.

Turbulenz

Turbulenz is a very old game engine which dates back to 2009 when WebGL and HTML5 were still in development. Turbulenz was not available as open source until 2013 when it was first made open source for free public use under the license of MIT. Turbulenz has experienced a huge demand following its classification as open source. It is packed with lots of features including 2D physics, 3D physics, music, video and additional services like leaderboards, multichat, payments and user data. Grab the source code from here.

PixiJS

PixiJS is a cross platform rendering library that enables you to create interactive, visually appealing graphics, and games without having any knowledge of WebGL API or deal device and browser compatibility issues. PixiJS is famous for its speed, it is one of the quickest 2D rendering engines out there. It is an open source software and has a large community which pushes its growth and development. PixiJS offers multi-touch interactivity along with other advanced features such as trimming and rotational packing etc. Grab the source code from here.

 Conclusion

In this list we have listed a variety of JavaScript engines for beginners to experiment with and develop their own original game. The engines listed here are only a few of the many engines available out there. Other engines such as Melon, Kiwim, GDevelop, Phaser and Matter.JS have their own pros and cons; but the engines listed here are the best among them all. Gaming engines and frameworks for your project should only be selected after thorough research, and deep consideration. This article has made this process a lot easier by listing the features of the top 5 best game engines.

How to wait or sleep the code execution

Sleep is a function that is present in most programming languages and is used to delay the execution of code for a specified time. JavaScript does not have this function, so we use the setTimeout() function to perform the same task. Although it does not work exactly as we expect from the sleep function, we will use it to build our own custom sleep function, in this article. For example, if we need to log three messages to the console with a delay of one second, we can’t do it using the sleep function as it is not available. But we can work around this by using the setTimeout() function.

 What is the setTimeout() method?

The setTimeout() method is used to set a timer to delay the execution of code. It executes the specified piece of code after the timer expires. A lot of devs who have worked with the sleep() function find setTimeout() to be confusing. This is because they mistake the setTimeout() function to be a version of the sleep() function. Unfortunately, the setTimeout() has its own rules and does not work the way the sleep() function does so JavaScript devs have to come up with ingenious solutions to make it work as a sleep() function. In this guide, we will look at several such solutions and explain how we can use the setTimeout() function to pause the execution of JavaScript source code and wait between consecutive lines of code. Unlike the sleep() function, if we just put a delay of one second using the setTimeout() method between the lines of JavaScript code, it does not work: setTimeout(1000) console.log("Showing after one second") setTimeout(1000) console.log("showing after another one second") The code in the example above will execute without any delay as if the setTimeout() function doesn’t exist. The problem with the code given above is that the setTimeout() method only delays the execution of the function that is passed to it as a callback function. However, we gave only one “delay” argument when it is actually supposed to get two different arguments. The first argument is supposed to be a callback function, and the second argument is supposed to be the “delay”. Now let’s try to do that and see what happens: setTimeout(() => console.log("showing after one second"), 1000) setTimeout(() => console.log("showing after another one second"), 1000) This time the setTimeout() function will work but not as it is supposed to, as both the console log messages will be displayed at the same time instead of having a delay of 1000 milliseconds between them.

 So why did setTimeout() fail?

The reason why setTimeout() fails in the example above is that the setTimeout() function itself works synchronously code but the call-back function inside the setTimeout() function creates a new entry in the asynchronous task queue which is executed after the specified time. Since the specified time in both the setTimeout() function was the same and they were executed at the same time due to synchronous code execution if javascript (with a delay of just a few milliseconds), all the entries in the asynchronous task queue run simultaneously. As you can see, setTimeout() is not an exact copy of the sleep() function, rather it just queues up code for later execution. So the question arises, how do we make it work like a sleep() function. We can do this by using increasing timeouts when calling the setTimeout() function: setTimeout(() => console.log("showing after one second"), 1000) setTimeout(() => console.log("showing after another one second"), 2000) This works because the new entry in the queue is created at approximately the same time, but those entries have to wait for different amounts of time to be executed. The method given above is the method that is used to delay the execution of some parts of code while the other parts run synchronously. However, if you want to halt the execution of the whole JavaScript code while asynchronously executing some other parts then you will need to create a custom sleep() function.

 How to Write a Sleep Function

In JavaScript, we can create a custom sleep() function by using promises, async, and await. This works exactly as a sleep() function would in any other language. However, this custom sleep() function needs to be used with the await keyword and should be called from within async functions. var sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))var repeatMessage = async () => { await sleep(1000) console.log("showing after one second") await sleep(1000) console.log("showing after another one second")} repeatMessage(); Now, by using this custom build sleep method, you can halt the execution of the javaScript code for the desired amount of time.

 Conclusion

JavaScript does not have the sleep() function by default to delay the execution of code but its asynchronous nature can be used to achieve the same task. The inbuilt setTimeout() method can be used to delay the execution of code but to truly make the code asynchronous and make it work like the sleep() function we need to use the promises, await, and async functions. In this article, we learned to create custom sleep() functions.

What are Async/Await Functions

As we all know, the single threaded nature of JavaScript makes it synchronous; So asynchronous functions are necessary to perform any asynchronous task. The Asynchronous functions allow us to perform one action without waiting for the previous action to complete. That means that there is an event loop that allows you to queue up a task (when it’s requesting for some resources) and move onto the next. JavaScript offers many features that can make the code asynchronous; async await functions are one of them. The async/await functions are just syntactic sugar on top of already present features. They provide a simple way to handle asynchronous code. The async/await functions can be interchanged with promises code and the code will work perfectly fine Human brains are not designed to handle asynchrony efficiently. The async/await functions allow us to write code that looks synchronized but executes it asynchronously. This article will assist you in learning about async and await functions.

 Why to use async/await functions?

Following are the reasons why async/await functions should be used code: We can write clean and concise code with a few errors using async/await. This will increase the readability of nested and complex code. Helps in Debugging. Errors can be handled in one place by using try/catch. The async/await functions have a proper error stack, unlike the ambiguous stack received by Promise, which makes it difficult to find where the error occurred.

 How to use async

Async is a keyword that can be used for the declaration of synchronous functions. Through the async function, you can make sure that you don’t break the thread of execution, which can be written like synchronizing promise-based code.

 Features of async Function

Works asynchronously through an event loop Always returns a value It checks that a promise returns, and if it doesn’t, JavaScript automatically wraps it with the promise it resolves to that value

 Syntax of async Function

The syntax of the async function is as follows: async function name([param1[, param2[, ...param3]]]) { statements} Here, the name represents the function name, params represent the name of parameters to be passed in the function, and statements contain the body of the function and one or more await expressions used within the async function.

 A Simple Example of async Function

const getData = async() => { var data = "Hello World"; return data;} getData().then(data => console.log(data)); Let’s take a look at another example: async function foo() { await 1;} The above function is equivalent to the following function: function foo() { return Promise.resolve(1).then(() => undefined)} Above example represents that the code after each await expression is likely to be in the callback i.e .then. Through the functions, the promise chain is automatically constructed step by step at each reentry stage. The return value forms the last step in the chain.

 How to use await

The purpose of the await expression is to wait for JavaScript before the return result of the promise. It is important to note that this will only queue an asynchronous function block, not the execution of the entire program.

 Features of Await Function

Can only be used within asynchronous blocks. Makes the code wait for the Promise to return a result. Only asynchronous blocks will be kept waiting.

 Syntax of Await Function

The syntax of await expression is as follows: [rv] = await [expression] Here, await represents any value to wait for or promise, rv returns the value if there is no promise, or else returns the expected value of the promise.

 A Simple Example of await Expression

const getData = async => { var y = await "Hello World"; console.log(y);} console.log(1); getData(); console.log(2); JavaScript executes code sequentially. In the example above we can see that the console.log(1) was printed first as expected. After this the getData() function was called where we initiated a variable with the name of y and we used the await keyword in it. The await keyword will cause the JS runtime to stop or pause the code in that line i-e where we have written “Hello world”. It won’t allow the execution of further code until the async function call returns the result. It will send this task to the task queue and the next lines of code will start to run. In the next line after calling the function getData() we are console logging the 2 to the console window. Hence we saw 2 before “Hello world”. Now after this when the async call function returns the result only then will the code resume to run again and hence we see “Hello World” at the end of the console window.

 Conclusion

The async and await functions are a great way of handling asynchronous code as they provide clear and concise syntax. In this post we explored the concept of async/await functions. In the first half of the article we explored what async/await functions are and why we should use them. Then we explored their features and syntax along with examples.

Top 5 Best JavaScript Form Validation Libraries

Form validation is a technical process of checking if the information that a user has entered is correct and if it’s according to the rules provided. Form Validation is used by almost every application, website, mostly during sign ups and login. The reason for using form validation is to ensure if the user is entering the correct information, and the information is according to the format specified by that particular application. In an ideal world every user would fill the forms with necessary and correct information but in the real world people frequently make mistakes; this is where form validation is required. Every Senior web developer is familiar with the complexity of form validation. So they use pre-written code from JavaScript libraries to set up form validation in their projects. Validation libraries can be used to carry out client-side form validation. Before client side validation was a thing, web pages reloaded every time a user entered information and if it was wrong they had to input the whole information again. Now on modern web pages if the user inputs the wrong information, an invalid info dialogue appears and the user can just modify the input instead of rewriting everything JavaScript form validation libraries enable web developers to customize forms, error messages and style them according to their project requirements. There are many form validation libraries out there which offer a ton of useful features such as better functionalities and enhancement of the design of a web page according to the modern requirements for web design; In this post we will list the top five of these libraries:

Just Validate

It’s a simple, dependency free, form-validation library that is compatible with the Bootstrap framework. It comes with customizable rules, submit form with ajax helper, supporting both client and server side form validation.

Validator

It is another lightweight, user-friendly form validator which works cross browser and can deal with all sorts of edge cases. It works with HTML input types such as email, url, text etc and comes with various customizable rules. It uses the new HTML5 types for unsupported web browsers. It also has a flexible error notification system.

Bouncer.js

It is the form validation library that was created to extend the HTML5 form validation; it’s a script that augments the native HTML5 form validation elements and attributes. With customizable rules, it also allows us to give users immediate feedback when they leave an input field instead of refreshing the page. Fields with errors are revalidated simultaneously as the user types and the error messages are removed immediately as soon as the user inputs valid information.

creditCardValidator.js

Data can be of any form in the input form fields. Often, we need to validate data like emails using regex or some information like credit card info. For validating the Credit card information, there is a library out there in the market known as creditCardValidator.js. It’s a simple JavaScript form validation library that’s used to validate credit card information such as the expiration date, name, number and CVV etc. It has the ability to detect the type of the credit card as well.

Pristine

Simple JavaScript form validation micro-library that’s used along HTML input attributes to create a customized form. This library does not focus on providing every kind of form validation; rather it focuses on the most important types. Thus it does not become bloated like some other form validation libraries.

 Conclusion

Form validation libraries allow the developers to put restrictions and set rules for the information entered by the user. This can be done by simple HTML and JavaScript as well but JavaScript libraries provide better functionality and enable the developers to set more complex rules with little to no effort. Some of the best JavaScript form validation libraries are listed above. They all are great at providing a user-friendly and easy to use form validator. Some of them come with extra features while others provide the basic features available for all. It’s up to you, what you want to achieve and what your requirements are.

Timing Events

Events that are fired at a specific time interval to execute the JavaScript code are known as timing events. They can be used to delay the execution of code or to execute a block of code repeatedly after a specific time interval. These events are called global methods as they are directly available in the HTML DOM and can be invoked from anywhere in the code. How to execute JavaScript Code after a specific time interval To execute JavaScript code after a specific time interval, the window object is used. There are two main/basic methods, used for timing events: setTimeout() function setInterval() function Both of the above functions are used to run a block of code provided to them as a function to execute at a specified time interval but with a subtle difference. Let’s start by looking at the syntaxes of both the functions and the differences between these syntaxes:

 setTimeout() function

The syntax of setTimeout() function is: setTimeout(function, timeInterval)// or window.setTimeout(function, timeInterval) Since we know that the window object is used to execute the JavaScript code after a specified interval of time however even if we do not use the window object with the setTimeout() or setInterval() function, they both will work the same. The setTimeout() function takes two arguments as parameters: One is a function that needs to be executed The second is a time interval in milliseconds, after which the function specified in the first parameter will be executed. The setTimeout() function is used to execute the provided function once after waiting for the time interval to be completed.

 How to Stop the Execution of setTimeout() function

Sometimes, we need to stop the execution of the function defined/called in the setTimeout() function before even the mentioned time is reached. For example, while loading the data from the server, we show loaders on the web application, when the data is fetched before the expected time, we can just stop the loader and show the data.

 clearTimeout() function

To stop the execution of the setTimeout() function, the clearTimeout() function is used:

 Syntax

The syntax of the clearTimeout() function is: clearTimeout(setTimeoutVariable) The clearTimeout() function just takes the variable name which was returned by the setTimeout() function. For example, if we have called the setTimeout() function: holdExec = setTimeout(()=>{ console.log(done);}, 5000) Now, to stop the execution of the setTimeout() function before the time interval gets completed, we have to provide the “holdExec” variable as an argument to the clearTimeout() function and the clearTimeout() function would go like this: clearTimeout(holdExec); If the function inside the setTimeout() function is not executed, then the execution of the setTimeout() function will be halted.

 setInterval() function

The setInterval() function and its syntax is almost the same as the setTimeout() function yet the only difference between them is that the setInterval() function keeps on executing the function continuously after hitting the time interval. The syntax of setInterval function is: setInterval(function, timeInterval) The setInterval() function also takes two arguments as parameters: One is a function that needs to be executed every time after the specified time interval. The second parameter is a time interval, after which the function will be executed again and again. Now, the question arises here, if the setInterval() function keeps executing the function continuously then how can we stop the execution? The next section will explain it:

 How to Stop the Execution of setInterval() function

Well, just like the clearTimeout() function, we also have the option of stopping the execution of the setInterval() function.

 clearInterval() function

To stop the execution of the setInterval() function, the clearInterval() function is used:

 Syntax

The syntax of the clearInterval() function is: clearInterval(setIntervalVariable) The clearInterval() function just takes the variable name which was returned by the setInterval() function. For example, if we have call the setInterval() function: holdExec = setInterval(()=>{ console.log(holding...);}, 100) Now, to stop the execution of the setInterval() function whenever we want, we just have to provide the “holdExec” variable as an argument to the clearInterval() function and the clearInterval() function would go like this: clearInterval(holdExec); The execution of the setInterval() function will be halted right when you run the above-mentioned clearInterval() function.

 Conclusion

JavaScript offers programmers a number of methods to asynchronously execute a block of code; these methods are called timing events. Timing events allow for periodic execution of JavaScript code; they also enable the programmer to delay the execution of certain blocks of code. In this tutorial we covered the basics of timing events; we learned what they are and how to use them in our code.

String Manipulation Methods

In JavaScript a string is a primitive data type (a data type which is not an object); it can consist of any series of characters inside single or double quotes. It can either be a constant or variable. Strings are used to store data in the form of text. They have zero-based indices. a string is not an array of characters but rather an object; and to change or manipulate a string some functions or methods are required. JavaScript provides various functions and methods to manipulate the value of a string. These methods help users to make changes with the string values, finding indexes of a particular character, or converting a string to lower/ upper case etc. In this post we will discuss some of the most common methods used for string manipulation: Note: The browser console is used for the demonstration of examples in this article.

 Methods used for String Manipulation

Now we will discuss the most common methods used for string manipulation: concat(), indexOf(), lastIndexOf(), charAt(), match(), replace(), split(), splice(), length(), substring(), search(), toUpperCase(), toLowerCase(), trim()

 concat()

Its purpose is joining more than one string together and returning a new string without changing the original string. let str1 = "Welcome"; let str2 = "to Linux Hint"; let str3 = str1.concat(" ", str2); str1; str2; str3; As already mentioned above I have used the browser console to output the values of these strings. The + operator can also be used to concatenate strings: let str1 = "Welcome"; let str2 = "to Linux Hint"; let str3 = str1 + " " + str2;

 indexOf()

It returns only the first occurrence of a word in a string, including the spaces. In case of no result it returns -1. This method is case sensitive: let str = "Welcome to Linux Hint";

 lastIndexOf()

The lastIndexOf() method gives the index of the last occurrence of the specified word in the given string. It searches the string from end to beginning but gives the index from the beginning. In case of no result, it simply returns -1. let str = "Welcome to Linux Hint. Linux Hint is a great platform for learning about trendy technology topics."; This method is also case sensitive:

 charAt()

It returns the character at a specific index in the string; The index starts with zero: let str = "Welcome to Linux Hint";

 match()

This method searches the string to match expressions and returns the result as an Array Object. If no result is found it returns null. let str = "Welcome to Linux Hint. Linux Hint is a great platform for learning about trendy technology topics."; A global search for ‘int’: If we do not use /g as an argument then only the first instance will be returned.

 replace()

It searches the string for a specific value and then replaces it with the given value. let str = "Welcome to Linux Hint. Linux Hint is a great platform for learning about trendy technology topics."; let str2 = str.replace("a great", "the best");

 split()

It splits the string into an array of substrings and returns the new array. It takes a single parameter which defines the character at which the array will be splitted. In the case of a simple (“ “) split without any given value, it splits through each character. let str = "Welcome to Linux Hint. Linux Hint is a great platform for learning about trendy technology topics."; let i = str.split(" ");

 slice()

It simply cuts a specific part of the given string and returns the isolated part. It takes either one or two parameters, the first one is the starting index and second is the ending index of the part to be isolated. In case of isolating an ending part, use a negative index. let str = "Welcome to Linux Hint";

 length()

It returns the length of a string, for an empty string, the length is zero. let str = "Welcome to Linux Hint";

 substring()

It takes two parameters, start and end, and returns the characters in these indexes excluding the end character. If the start argument is greater than the ending argument, it’ll simply swap the values. let str = "Welcome to Linux Hint";

 search()

It searches a word in the string and returns its index. It returns -1 when no match is found. let str = "Welcome to Linux Hint";

 toUpperCase()

Simply convert the string to upper case letters. let str = "Welcome to Linux Hint";

 toLowerCase()

Simply convert the string to lower case letters. let str = "Welcome to Linux Hint";

 trim()

This method is used to remove all the whitespace characters (space, tab etc) from both sides of the string: let str = " Welcome to Linux Hint ";

 Conclusion

Unlike in some other languages, strings are not arrays of characters but rather are a separate data type. They are objects and have different properties and methods which can be used to manipulate them according to our needs. In this post we discussed some of the most commonly used methods used for string manipulation.

What are JavaScript Multidimensional Arrays

An array is a variable type present in most programming languages which contains multiple values of homogeneous data. The simplest arrays store data in a linear form and are known as one-dimensional arrays. In JavaScript multidimensional arrays are simply arrays within arrays; the most simplest of which are two dimensional arrays known as matrices; We can create arrays with any number of dimensions. Some programming languages like C# do support true multidimensional arrays while others like JavaScript just have nested arrays. The multidimensional arrays are known as jagged arrays; in jagged arrays each array in the parent array can have a different number of elements. Note: The browser console is used for the demonstration of examples in this article.

 What is a 1D array

One dimensional arrays are used to store a single series of data like the name of all the animals present at the zoo or the roll numbers of students in a class. But when it comes to storing more complex data like the pixel matrix of an image in a single variable then we need multidimensional arrays. var num = [1,2,3]

 How to declare a 2D array

In JavaScript, declaring a 2D array is very simple. Just put two arrays (separated by commas) in a parent array and you will have a 2 dimensional array: var nums = [[1,2,3],[4,5,6]]; For better readability we can write it in this way as well: var nums = [ [1,2,3], [4,5,6] ]; Now it looks very similar to a matrix.

How to declare an Nth-Dimensional array

In JavaScript you can have multidimensional arrays up to the Nth dimension meaning you can add as many dimensions to your arrays as you require. Following is an example of a three dimensional array: // Declaration of a 3-Dimensional array threeDimensionalArray = [ // two 2-Dimensional arrays within a 3-D array [ // two 1-Dimensional arrays inside a 2-D array [], [] ], [ // two 1-Dimensional arrays inside a 2-D array [], [] ]];

 How to access, assign and modify values of elements of multidimensional arrays

To access an element present within a 2D array we need to provide two indices instead of just one e.g. to access the first element of the first row of the 2D array/matrix we will use the following syntax: num[0][0]; Similarly for the first element of the second row we will use: num[1][0]; Similarly, for higher dimension arrays we will use as many indices as the dimensions of the array. If we need to access each element of the array in a sequence then using nested loops is the best option: var num = [[1,2,3],[4,5,6]];for (let i = 0; i < num.length; i++) { for (let x = 0; x < num[i].length; x++) { console.log(num[i][x]); }} In the above example the first loop, loops through the rows of the matrix while the second loop, loops through the columns. The second/nested loop iterates through the columns until there are no columns left then it terminates. The first loop then goes to the next row and the nested loop again starts from the 0th column of the next line. We can assign values to a multidimensional array when we are declaring it (as shown above in the 2-D array declaration section). We can also modify these values later in the following way: var num = [[1,2,3],[4,5,6]]; num[0][0] = 99; console.log(num[0][0]);

 Methods for Multidimensional arrays

We can use all the methods of one-dimensional arrays like push(), pop(), shift(), unshift on multidimensional arrays as well. These methods can be used to add elements in the child arrays as well as add more arrays to the parent array. E.g if we want to add another row to our two dimensional array then we will use the push() method in the following way: var num = [[1,2,3],[4,5,6]]; num.push([7,8,9]); console.log(num);

 Conclusion

One dimensional arrays are best when it comes to similar kind of data that needs to be stored in a linear form; but when it comes to complex data we do need multidimensional arrays e.g if we need to represent a chess board which has eight rows and eight columns we can use multidimensional arrays. In this post we learned all about multidimensional arrays, how to declare them, assign them values as well as accessing and modifying the values of the elements present within multidimensional arrays. Moreover we also learned that all the methods related to one dimensional arrays are also applicable on multidimensional arrays.

Operators

In real life you’ve seen how we add, subtract two values. Similarly, in a programming language, this action is performed through the help of operators. In simple words, mathematical or logical operations can be performed through the use of operators. Operators perform these functions on single or multiple operands to produce results. Here, operands are the data values on which operations are being performed. Like any other programming language, JavaScript also uses various operators. It’s helpful as it makes the task of comparing and manipulating values easy for the user. In this article, we’ll discuss various operators along with their usage and examples.

 Type of operators

There are various operators available, some are listed below:
    Arithmetic Operators Assignment Operators Comparison Operators Logical Operators String Operators
Let’s understand these operators one by one with examples for better understanding.

 Arithmetic Operators

Arithmetic operators help in performing all the mathematical basic calculations like addition, subtraction, multiplication, and division. Following are various Arithmetic operators:
Operators Name
+ Addition
Subtraction
/ Division
* Multiplication
% Remainder
++ Increase by 1
Decrease by 1
** Exponential (Power)
Example of Arithmetic Operators let x = 3; let y = 2;// addition console.log('x + y = ', x + y); // 5// subtraction console.log('x - y = ', x - y); // 1// multiplication console.log('x * y = ', x * y); // 6// division console.log('x / y = ', x / y); // 1.5// remainder of 3 / 2 will be 1 console.log('x % y = ', x % y); // 1// increase by 1 console.log('++x = ', ++x); // x will be 4 console.log('x++ = ', x++); // prints 4 and then increased to 5 console.log('x = ', x); // 5// decrease by 1 console.log('--x = ', --x); // x will be 4 console.log('x-- = ', x--); // prints 4 and then decreased to 3 console.log('x = ', x); // 3//exponentiation console.log('x ** y =', x ** y); // 3 power of 2 is 9

 Assignment Operators

In Javascript, assignment operators are used to assign some values to a variable. For example: let x = 3;const y = 5; Here, x and y are variables that are assigned values 3 and 5 respectively. Following are some assignment operators:
Operators Name
= Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division Assignment
%= Remainder assignment
**= Exponentiation assignment
Example of Assignment Operators let x = 3; // Assigning value using assignment operator// addition assignment console.log('x += 3', x += 3); // 6, now x = 6// subtraction assignment console.log('x -= 2 ', x -= 2); // 4, now x = 4// multiplication assignment console.log('x *= 2 ', x *= 2); // 8, now x = 8// division assignment console.log('x /= 2 ', x /= 2); // 4// remainder assignment console.log('x %= 2 ', x %= 2); // 0//exponentiation assignment let x = 5; console.log('x **= 2', x **= 2); // 25

 Comparison Operators

Comparison Operators work by comparing two values and returning true and false:
Operators Name
== Equal To
!= Not equals to
=== Strict equals to
!== Strict not equal to
> Greater than
< Less than
>= Greater than or equals to
<= Less than or equals to
Example of Comparison Operators: // equal operator console.log(3 == 2); // false console.log(3 == '3'); // true// not equal operator console.log(3 != 4); // true console.log('world' != 'world'); // false// strict equal operator console.log(7 === '7'); // false console.log(6 === 6); // true// strict not equal operator console.log(8 !== '8'); // true console.log(3 !== 3); // false

 Logical Operators

Logical operators are used to handle logical operations on data values, as a result, they return a boolean value:
Operators Name
&& Logical AND
|| Logical OR
! Logical NOT
Example of Logical Operators: // logical AND console.log(7==7 && 7==7); // true, AND operator works when both given statements are true console.log(7==7 && 7==87!=7); // false, one of the statement is not true// logical OR console.log(7==7 || 7!=7); // true, OR operator works when one of the given two statements is true// logical NOT console.log(!7==7); // false, would’ve been true if the expression was not true.

 String Operators

String Operators are used to join two or more strings or a number and a string. Example of String Operators: let x = 5 + 25; // 30 let y = "5" + 5; // 55 let z = "World" + 5; //World5

 Conclusion

TypeOf operators are used to tell the program regarding which mathematical operation should be performed. In this article, we learned various operators, how they are used, and their functionality. The operators help users to perform difficult tasks with ease, and logically. Each specific operator is available for the user to implement a particular functionality in their program. I hope this helps you with a better understanding of operators, and in general, as the core concepts in every programming language are interlinked.

JavaScript vs Python

Python is a powerful and versatile, object oriented, general-purpose programming language that is widely used in specialized applications, including Web applications, Artificial intelligence, Machine Learning and Game development. In web development Python is used in server side development. This is where we can compare it with JavaScript. JavaScript is a programming language that follows the ECMAScript specification and is used in both client and server side development; it is most commonly used in web development to add interactivity to static pages. It is a well-liked scripting language that is used by everyone from entry level web devs to big companies like Google and Facebook. Following are some differences between Python and JavaScript: Python is being used in virtually every scientific application because it is good at handling math intensive processes. It is a high level, object oriented, general purpose programming language which is being used in various fields such as computer vision, computer science education, data science, artificial intelligence, server side web development etc. JavaScript on the other hand is an object based, scripting language that is mostly used in web development; it can also be used in game and mobile app development using different frameworks such as React.JS. Python and JavaScript are syntactically different as well. Python uses indentation to specify code blocks whereas JavaScript uses curly brackets. In python a new line marks the end of a statement while we can use an optional semicolon to mark the end of the statement. In Python variables are conventionally named using lower case letters which are separated by (_) underscores. variables names are conventionally written in lowerCamelCase. Python uses # to mark comments while JavaScript uses //. JavaScript is a weakly typed programming language which does not support procedural programming whereas Python is strongly typed and has procedural programming.

 Differences between JavaScript and Python

JavaScript Python
JavaScript is scripting language that follows the ECMAScript specifications Python is a general purpose object oriented language designed with the philosophy of being easily readable
It is used on both client/front-end and server-side/back-end It is primarily used for server-side development
It executes faster than Python It is sluggish to execute compared to JavaScript
It is harder to learn It is easier to learn
It is ideal for creating front end of websites It is excellent for performing data analytics, machine learning and other math intensive processes
It is weakly typed / dynamically typed language It is strongly typed / statically typed language
It does not have procedural programming It has procedural programming
JavaScript is a poorly designed programming language Python is one of the better-designed languages
JavaScript is used in mobile application development Python is unsuitable for mobile app development
JavaScript has a small standard library. Python offers a large standard library
JavaScript has no libraries for data analytics, scientific computing, and machine learning. Python offers numerous libraries for data analytics, scientific computing, and machine learning.
Java-Script primarily works on floating-point variables Python offers support for various numerical data types
JavaScript code can run directly on a server Python source code is executed in interpreters.
JavaScript does not have integrated REPL Python has integrated REPL
UTF-16 should be used to encode JavaScript source code. Python source code is encoded in ASCII by default
Curly brackets {} are used to highlight blocks of code. Python uses indentation to highlight a block of code
JavaScript does not care if incorrect arguments are passed to a function Python gives an error if incorrect arguments are passed to a function
JavaScript has no concept of mutable or immutable Data types On the other hand Python does support these Data types

 Conclusion

Python and JavaScript have all the basic necessary elements which are required to create powerful programs. So answering the Python vs JavaScript question is really difficult. Each programming language is developed with its own philosophy. It is specially built to be better at performing certain tasks. JavaScript has been specifically designed to run on the client’s browser so it has an edge when it comes to client side web development. However with frameworks and libraries such as NodeJS and ReactJS, JavaScript is becoming more popular, JavaScript is now even being used in mobile app, game and server side development. Python on the other hand is primarily used in server side development, artificial intelligence, machine learning, and other math intensive processes.

What is the difference between JS and JSX

JavaScript is an ECMAScript following scripting language which allows developers to make their web pages more interactive. Every time a webpage loads something, or a slideshow plays, or an animated picture is displayed, JavaScript is involved behind it. Basically it adds life and creativity into a website, making it more engaging. JSX is just a syntax extension of JavaScript which allows users to write React components; React is an open source frontend JavaScript library for building complex UIs; it allows the programmers to create complex UIs from smaller components. JSX or JavaScript XML combines HTML and JavaScript, making the code easier to read and understandable for the user. JSX combines interactivity with markup rather than separating the two. It makes it easier to visualize DOM. In JSX we can directly write HTML tags inside JavaScript code.

 How are JS and JSX different?

Both JS and JSX are interchangeable but the difference lies in how the user interface is created and how functionality is split across the application. For JS, a simple HTML is written first and the JS is written within the script tag as shown: <div> <h1>Fruit List</h1> <ul id="fruit-list"> <li>Orange</li> <li>Mango</li> <li>Pear</li> </ul> </div> And then the JavaScript is added which will perform the functionality: <script>function addItemToList() { // Add item } </script> But the similar code of JSX in React starts with a fixed HTML file: <div id="root"></div> And then the code is written which looks similar to HTML, but is JSX: function FruitList(props) { return ( <div> <h1>Fruit List</h1> <ul> <li>Mango</li> <li>Pear</li> <li>Guava</li> </ul> </div> ) }; In this way the functionality is also split up in components and hence making complicated applications easier to understand. JSX isn’t necessary to use as React can be written with both JS and JSX, but JSX makes it easier for users to make React applications, as it is similar to HTML. It makes it easier to write and update HTML code, thus functionality is easier to handle.

 Conclusion

JS is simply a scripting language, adding functionality into your website. JSX is an addition to the JavaScript syntax which is a mixture of both HTML and JavaScript. Both JS and JSX are interchangeable but JSX makes the code easier to understand for users. JSX is popularly used in React, as it makes the job of building an application much easier.

What is the purpose of array.find() function

It can be figured out by the fact that while working, one usually has to deal with the data that is being stored in the arrays. What can be the most recurrent thing to perform in an array? That is going to be the array search where you find a specific value in an array and you find it upon completing or satisfying the desirable condition being set out. While working with data present in arrays, sometimes, you might want to get the index of a certain element, get confirmation of whether a certain element is present within the array or not, in form of a boolean value, or you might want to form a new array which contains all the elements that you searched for. Modern JavaScript offers many built-in methods to perform such tasks; The array.find() is one of these methods.

 How to use array.find function

The array.find() method is used to search for and return the first occurrence of an element/item in an array that passes a certain condition. When you need a single match stick from the matchbox, go for the find function. Condition for array.find function For an element to be returned, it needs to fulfill the specific condition or a test that is being set out by the user. If the element is found in the very beginning where the condition gets fulfilled, the array.find function will not go through the remaining elements of the array. Applicability of array.find function You must be aware of the filter() method? The method that we use to find multiple values. The array.find() method and array.filter() method are very similar but we use array.find() method when we require the single existence of the method. When the array.find() method is unable to find anything, it returns an “undefined” value. Therefore if you only require or need a single value, use the find() method. For multiple values to be returned or found, use filter() instead. Syntax of using array.find function Using such a method is not complicated; The only argument that this method requires is a call-back function. Here is the most basic form: array.find(callBackFunc); // Done! Point to considerNote: The originality of the array doesn’t get affected.

 Parameters or Arguments of array.find function

Callback function: A function that will be executed for every element of the array callBackFunc(currentElement, index, arrayName), The callBackFunc further takes three arguments:currentElement: The current element of the array.index: The place of the current element within the array(Optional).arrayName: A reference to the original array(Optional)thisParameter: This parameter is used as the ”this” inside the callback function(Optional). So, the whole syntax of array.find() function would go like this: array.find(callBackFunc(currentValue, index, arrayName), this) Now let’s try some examples and grasp the concepts of array.find() method with clarity.

 Examples

First, let’s start with a simple array of names: Example 1: Let’s take another example in which we take an array of three names and we want to know whether that array contains a specific name or not. We simply search that array by the specific name: var nameFound = ['James', 'Paul', 'Nathan'].find(function(name) { return name === 'Paul';}); If that array contains our desired name then we simply print on the console “name exists”. if(nameFound){ console.log(nameFound + "exists");} What is going to be the output? Output Yes, you got it right. It will be “Paul exists”. Now. let’s have another example in which we will try to find a value inside the object using array.find() method: Example 2: Here we have a list of client objects as well as their bill let clients = [{ name: 'pvt ltd', bill: 90}, { name: 'pharma ', bill: 150}, { name: 'realtor', bill: 200}]; We are going to apply the find method in such a way that the client whose bill is greater than 90 will appear right in front of us. console.log(clients.find(c => c.bill > 90)); And the result is going to be: Example 3: Let’s suppose we have a list of colors. const colors = [ "blue", "grey", "pink", "violet"]; Now the statement for finding the color with the first letter as “g” will go like that: console.log(colors.find(color => color.startsWith("g"))); And the output will definitely be the grey color.

 Conclusion

In this article, we have explained all the aspects of the array.find() method. Starting with the description, we have explained the functionality of the array.find() method in a precise manner. We have covered almost every aspect of the array.find method. Firstly, we have described the basic purpose of the array.find() method and then by proceeding with the syntax, parameters, when to use, how to use, and examples, we have acquired a fine level of understanding for the reader. The readers can easily understand the working of this method as it was briefly explained with three practical examples.

How to run a NodeJS module in a browser

NodeJS isn’t a programming language but rather it only provides a runtime environment for the execution of JavaScript code. This makes it a server side technology. Running and executing processes on server, and hence accomplishing tasks. Module is an encapsulated code, separated from main application code with functionality that can be reused throughout your code. NodeJS provides us with various repositories of open source modules that can help us achieve various development tasks. But these modules are only useful if you’re building a server side application. So a question arises that what should a developer do if they want to build a client side JavaScript application? Well this article will give you the answer, from how to install NodeJS to running its modules on browsers, this article provides you with everything.

 Node JS Installation

Before anything, you need to have NodeJS installed. For this visit the link by clicking on this and download the LTS (Recommended) version. NPM which is Node Package Manager will also be automatically installed on your system along with the installation of NodeJS. NPM is helpful as it’s a package manager that helps in downloading and integrating packages into JavaScript code. Now, to check whether NodeJS and NPM have been installed on your device you can run the following command: Node -v npm -v

 How to install NodeJS module

There are two ways you can download the module, locally and globally. The difference is that the globally downloaded module can be accessed easily by all the projects on your system. Whereas, local modules can only be accessed by your current project. Command for Downloading Module Locally: npm install [module_name] To better understand this, we’ll install the Express module, which is used for building APIs etc. npm install express It’ll provide you with the following output. A new folder will be created automatically by NPM by the name “node_modules”, It will store all your modules and packages.

 Command for Downloading Module Globally

It’s better to install modules both locally and globally. Reason is that it’ll allow you to share the installed command and at the same time you’ll be able to protect the dependencies. Run the following command: npm install -g [module_name] In the following example we’ll install dateformat package globally: npm install -g dateformat

 How to Use the Package with JavaScript

Through the following way, the NPM package can be used into the JavaScript: var dateFormat = require('dateformat');var now = new Date(); console.log(dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT")); But this will cause an error: Why is that? Well, the reason is that NodeJS is a server-side technology. It comes with it’s perks, but a major drawback is you can not run your module on your browser without installing some tools.

 How to run modules using Browserify on Browsers

Being able to run a node module on the browser is extremely beneficial. Users can use already existing modules on the client side JavaScript application without having to use a server. But how can this be done? Well, here comes a tool called Browserify. Browserify is a command line NodeJS module that allows users to write and use already existing NodeJS modules that run on the browser. As it is a command line tool, users have to convert their script written with NodeJS to JavaScript file so that it can be added with HTML script tag. Let’s understand the process step by step: Firstly, we have to install Browserify. For installation following command needs to be run: npm install -g browserify Now, the following command needs to be run so that you can run your application in the browser without any errors. browserify name-of-file.js -o bundle.js This command will resolve all the dependencies and combine your source code into a file that can be included with a single script tag. But note that these commands need to be run each time you make changes in your original source code. Now, just replace the name of the source in the script tag with “bundle.js” in the html file. <!DOCTYPE html><html><body><script src = "bundle.js"></script></body></html> Now, if your run this HTML file and open the console, it will not display any error and the result will be displayed: In this way you can easily use your script through a single script tag inside an HTML file. Through Browserify, you can easily run your modules on browsers without any error.

 Conclusion

Running a module of node js on a browser is extremely beneficial and provides ease to the user. In this how-to guide we learned how to run our node module in a browser. As NodeJS uses server side technology , it becomes difficult for users to run its module on the browser. Hence, Broswerify comes into use. With its easy to install commands, making node modules browser compatible becomes an easier task. Hence, creating a client-side JavaScript application becomes easier for users.

What is the match() method

The match method is an inbuilt JavaScript method that searches a string against a regular expression. The regular expression is the value we want to search for. If the searching match is found, it returns an array object containing the regular expression. If the search match is not found, it returns a null value In this post we will have an in-depth discussion about the match() method; We will start off by looking at the syntax of the match() method:

 Syntax:

string.match(regExp); String is the variable in which we are searching and myexpression is the expression we are searching for.

 How does the match() method work

Now, let’s look at a few examples to better understand the JavaScript match method: Note: The browser console is used for the demonstration of examples in this article. var str = "Hello and Welcome to Linux Hint!"; console.log(str.match('Welcome')); The match method returns only the first occurrence of the regular expression inside the string. If we need to check for multiple occurrences then we will need to add the g modifier. The g modifier is a global search modifier that searches the expression at all instances. This returns all the matched elements. If we don’t put this modifier then only the first match will be returned: var str = "Hello and Welcome to Linux Hint!"; console.log(str.match(/el/g)); We can also use the i modifier with the match method as well. This performs case insensitive matching. In simple words, the match method by default performs a case sensitive search but when we use the i modifier it ignores case sensitivity. var str = "Hello and Welcome to Linux Hint!"; console.log(str.match(/linux/i)); The match method returns null if no match is found: var str = "Hello and Welcome to Linux Hint!"; console.log(str.match('my')); If we do not give any parameter the match method then it returns the array object containing an empty string: var str = "Hello and Welcome to Linux Hint!"; console.log(str.match());

 Using special characters in regExp

We can use different special characters in our regular expressions to carry out more complex searches. The \d sign can be used to search for the first digit in the regular expression: var str = "abcdefghjkl123456789"; console.log(str.match(/\d/)); If we want to get all of the digits present in the string: var str = "abcdefghjkl123456789"; console.log(str.match(/\d/g)); The \D sign will output an array of object that contains every character that the /d sign ignores: var str = "abcdefghjkl123456789"; console.log(str.match(/\D/g)); A character followed by the $ sign can be used to check whether that is the last character of the given string: var str = "Hello and Welcome to Linux Hint!"; console.log(str.match(/!$/));

 Difference between the match and search methods

The search method searches for the given parameter, if found, it returns the index of that expression in the string whereas the match method returns the expression inside an array object: var str = "Hello and Welcome to Linux Hint!"; console.log('match() method: ' + str.match('and')); console.log('search() method: ' + str.search('and')); If the match is not found then the search method returns -1 whereas the match() method returns null: var str = "Hello and Welcome to Linux Hint!"; console.log(str.match('near')); console.log(str.search('near')); Note: You can put your JavaScript code in a script tag and then run your html file in the browser or just create a different file with js extension and reference it inside the html file using the script tag.

 Conclusion

The match() method is used to find a regular expression (regExp) in a string. The match method returns an array object containing the regular expression, its index, group and the original string. In this how-to guide we learned how to use the match() method to search for a regular expression inside a string. Then we learned to use special characters and modifiers with the match() method to perform more complex searches. Moreover, we also discussed the difference between the search() and match() method.

What is eval() function

What do you do when you have an expression or a statement and you want to evaluate it? The eval() function is there to facilitate you., we use the eval() function to evaluate as well as assess an expression or a statement. There is much more about that. Let’s proceed through everything we need to know about eval().

 What is the eval() function?

Whenever you tackle javascript and you come to a point where you desire to evaluate an expression, the eval() function is there. It is, in fact, a global function of JavaScript which we use to assess the designated string as a code of JavaScript and then carry it out or perform the desired operation on it. Additionally, the eval() function works differently in different scenarios. For an argument to be evaluated, if it’s an expression, the eval() function takes it as an expression and then evaluates it. In case of an argument to be a statement of JavaScript, the eval() function is going to deal with it as a statement and then executes it. Hint: The eval() function does not perform the arithmetic operation as this operation is carried out by JavaScript automatically.

 Syntax for eval function

Here is the syntax for the eval function: eval(string) The eval is a function whereas the inside value is known as a parameter. As you can see, the string is the parameter. Depending upon the nature of the program, the string can be an expression of JavaScript, a sequence of statements, or even a single statement.

 Condition for the Return value

For the eval() function to perform and retrieve results, we need to put some values into the function. In case of an empty value, it will return undefined.

 Examples of the eval function

Let’s try a couple of examples to demonstrate and understand the true working of the eval() function. Example 1 We are going to give two examples in this regard and let’s see if you can judge the right answer: a = eval(new String('5+5')); b = eval('5+5'); console.log(a); console.log(b); What do you think? What is going to be the output for a and b Let’s talk about the former example first. In that case, suppose we have specified the constructor of a string, the eval() function will return the object of the string. It won’t perform the operation of the string. Hence, the output for a will be an object of the string that will contain “5 + 5”, not the answer to this arithmetic operation. Now let’s come to the variable b, in the argument of eval() function, we can’t see any string inside. Therefore, the eval() function is going to evaluate the expression and the answer will be 10 after being evaluated. Output Example 2 In this example, we will try to pass variables to the eval() function and see what will happen: var f = 6, g = 7, h = 8, sum, mul, sub; sum = eval(" f + g + h "); mul = eval(" f * g * h"); sub = eval(" f - g"); console.log(sum); console.log(mul); console.log(sub); In the above code, we clearly initiated the variables f,g, and h with values. Then we performed some basic arithmetic operations in order to assess the functionality of the eval() function. That’s how the eval() function behaves in case of no string. It evaluates the expression being put inside. The result is going to be Result Example 3 Let’s try to put something more complex like calling a function and assigning that function call to a variable: var test;function func1(m, n){ return m * n;} eval("test = func1(30, 20);"); console.log(test); How are you going to assess the output? It’s simple. Here’s how: First, we declared the variable test. Then we introduce the function as “func1” which consists of two arguments “m” and “n”. The return value of that function is going to be the multiplication of these two parameters “m” and “n”. The result is going to be stored in the test variable and the function will be called by the eval() function. Hence, the output is going to be

 Limitations

It is considered insecure Slow The code gets unreadable while dealing with it

 Conclusion

In this topic, we have achieved a fine level of understanding of the eval() function, the functionality of the eval() function as well as its behaviors in specific conditions. We started our article from the description of the eval() function, after that, by stating out the syntax, limitations, and examples, we have covered every aspect of the eval() function so that the reader can understand the concept in the best possible way.

What is a ternary operator

The ternary operator is a conditional operator which can be used as an alternative of the if/else statements code. It helps to write concise and clear code; in this tutorial we will learn to use the ternary operator to write conditions in a more clear, concise and shorthand syntax.

 What is a Ternary operator

A ternary operator works in the same way as the if statements. It evaluates a condition, if true, it executes a block of code related to that condition. Let’s look at the syntax of the ternary operator: condition ? expression1 : expression2 The ternary operator will first evaluate the test condition and then: Execute the expression1, if the condition is true Execute the expression2, if the condition is false The ternary operator is called as such because it takes three operands, Now, let’s write a few examples to see how the ternary operator really works: // code snippet to check if student is Adult or not let age = prompt('Enter your age:');// checking age using ternary operator let result = (age >= 18) ? 'an Adult' : 'not an Adult'; console.log(`You are ${result}.`); Suppose the user enters 18. Then the condition age >= 18 is checked which evaluates to true. So, the first expression will be assigned to the result variable. And if the user enters something like 15 then the condition evaluates to false and the second expression pass is assigned to the result variable.

 How to use ternary operator to replace of if/else statements

In JavaScript, the ternary operator is used as a replacement for some if/else statements. For example, in the code snippet given below the if statements can be replaced: // check whether a student passed a test or not let numbers = 70; let result;if (numbers >= 50) { result = "You have passed the test.";} else { result = "You failed the test.";} console.log(result); With: // ternary operator to check the test result let numbers = 70; let result = (numbers >= 50) ? "You have passed the test." : "You failed the test."; console.log(result);

 How to use nested ternary operators

Ternary operators can be nested inside other ternary operators as expressions: // code snippet to check the grade of the student let n = 83; let grade = (n >= 80) ? "A" : ((n >= 70) ? "B" : ((n >= 60) ? "C": ((n >= 50) ? "D": "F"))); console.log(`Your grade is ${grade }.`);

 Conclusion

Ternary operators are used to assign different values to a variable based on different conditions. In most cases it is not recommended to replace if/else statements with ternary operators as it can make code harder to read and understand, but in some cases a single line ternary operator in place of multi line if/else statements can be useful. In this how-to guide we learned to use the ternary operator; Moreover we also learned about nested ternary operators.

What is set object

In JavaScript sets are very similar to arrays; but unlike arrays they cannot hold duplicate values. They were introduced in the ES6 version of JavaScript and used to create a collection of unique values. These values can be anything from simple primitive values like integers to more complex object types such as object literals. In this post we will learn all about Javascript sets; so let’s get started by discussing the default methods of set objects present in ES6 JavaScript. Note: The browser console is used for the demonstration of examples in this article.

 Methods of Set

There are a few useful methods of Set as well that we will discuss in this post to have a better understanding of Sets. .add .size .has .delete .clear

 Sets

In this example we will create a set that has a list of students; to create a set of Students, first, create the set: let students = new Set();

 How to add elements in Set

Now, to add values/items in the newly created set of students, the add() method is used: students.add("John"); students.add("Bob"); students.add("Harry");

 How to get the size of the Set

To know the size of the Set, the size method is used. For example, to know the size of the students set: console.log("The length of the set is: " + students.size);

 Values of Set

If we try to add a value in the set which already exists in it, the set would not take that new value. For example, if we add “Bob” again into the students Set: students.add("Bob"); And console the students set or check the size of the students Set: console.log(students); Or: console.log(students.size); You can see that the “Bob” is not added twice and the size of the students Set is the same as before.

 How to know if a Set has some specific value or not

To know or check whether a set has some specific value or not in it, the .has method comes into help. For example, to know if the students Set has “Bob” in it or not, the following code snippet will be used: console.log(students.has("Bob"));

 How to remove an element from the Set

The .delete method is used to remove a set element. For example, to delete “Bob” from the students Set: students.delete("Bob"); Now, if we again check whether the students Set has “Bob” as an element or not: console.log(students.has("Bob")); The above “has” method will return false and you can verify it.

 How to delete/clear all the elements from a Set

To delete all the elements that existed in a Set of javaScript, the .clear method is used. For example, to delete all the student names from the students Set, the clear method would go like this: students.clear(); Now, if we check the size of the students Set to verify: console.log(students.size); The “0” value is verifying that there is no element in the students Set.

 Converting a JavaScript array into a Set

We can easily convert an array into a set by giving it as an argument to the new Set() constructor: var arr = [6, 10, 18, 3, 3, 9, 6, 7]; var set = new Set(arr); console.log(set);

 Conclusion

As a JavaScript developer you will come across many instances where you have an array that contains many elements (some of which are duplicate) and you want to convert it into a unique array. While it can be done using different techniques such as combining conditional statements with loops, the convenient method is using set(). In this how-to guide we learned to create sets along with learning about the set methods present. Moreover we also learned to convert a JavaScript array into a set.

JavaScript Loops – A Guide for Absolute Beginners

In computing, almost all programming languages support the idea of loops. In computing, loops are a set of instructions that allow the programmer to do something repeatedly in a quick and efficient manner. Loops iterate/repeatedly execute through a block of code until a certain condition is met. All high-level programming languages provide several different types of loops. The syntax of these loops may be different but they are used to perform the same tasks. These loops are interchangeable but some are specifically built to be used in some specific conditions. The most popular loops present in most programming languages are for and while loops; here we will discuss them along with their extensions which are present:

 How to use the for loop

The most simplest and commonly used loop is the for loop; for loops are preferred over other loops when the programmer knows the definite number of times the loop is going to run. Let’s take a look at the syntax of the for loop to understand why: for ( initialization ; condition ; variable modification ) { // code statements to be executed} The for loop takes three arguments, initialization, condition and variable modification: The first argument i.e. initialization runs only one time before the execution of the loop; It initializes a variable which is used in the condition for the loop. The second argument i.e. condition is evaluated before every iteration; the loop terminates when this condition is satisfied. The third and the last argument variable modification is used to modify the value of the variable used in condition after every iteration of the loop. The arguments of the for loops specify the definite number of iterations it is going to run. They specify the starting point (initialization) and the ending point (condition) of the loop. Although all of the arguments are optional (the for loop will run even if you do not specify the condition) however it is not recommended to leave the condition argument empty as it will create an infinite loop which can crash your browser. Now let’s try an example to better understand for loop: Note: The browser console is used for the demonstration of examples in this article. In this example we will count down from 10 to 1 using a for loop: for (let index = 10; index >= 1; index--) { console.log(index);} In the above example: Index is initialized to 10 Then the condition is checked, since the index is greater than or equal to 1 condition is true the loop is executed and the value of index is printed to the console After the first iteration the index variable is decremented by one. The operator reduces the value of the index by one. Then the condition is again checked; As the condition is still true the loop is again executed. This process keeps recurring as long as the condition for the loop remains true. When the value of the index recheas 0, the condition greater than or equal to 1 is no longer true and the loop terminates. We can perform any operation on the variable in the last argument of the for loop statement: for (let index = 2; index < 500; index*=2) { console.log(index);}

 How to use while loop

While loops only take one argument which is the condition for the loop: They are mostly used when the code has to run an unknown number of times until the condition is satisfied: while (condition) { // Statements} Let’s take a look at an example where we will generate a random number by using the Math.random() method inside the loop; The loop will keep running until the Math.random() method produces an odd number: runLoopAgain = true; while (runLoopAgain) { num = Math.random().toFixed(1)*10; if (num % 2 != 0) { runLoopAgain = false; } console.log(num);} In the above example we first declared a boolean named runLoopAgain and assigned it a value i.e true. The while loop evaluates the condition before the execution of the loop; as the variable runLoopAgain is the condition of the loop and is true the while loop is executed. Inside the body of the while loop we have used the random method of the Math object along with the .toFixed method to get a random number between zero and nine. Then we have used a conditional statement to check if the number is divisible by two (to check if it is even or odd). If the number is odd then the runLoopAgain variable will become false and the loop will terminate otherwise the variable/condition will remain true and the loop will keep running. The tasks that we performed in the above examples using the for loop can also be performed with while loop: let i = 10; while (i >= 1) { console.log(i); i--;} let i = 2; while (i < 500) { console.log(i); i*=2;}

 How to use the break statement in While loop

The break statements can be used inside the loop’s body to terminate the loop. Let’s look at an example: let i = 2; while (i < 20) { if (i % 5 == 0) { break; } console.log(i); i+=2;} In this example I have used a while loop to print out every even number which is less than 21 but I am only getting even numbers less than 9; why is that? This is because I have used a break statement which terminates the loop if the even number is a multiple of 5. We can use the break statement to have different conditions for the termination of a while loop inside the loop’s body:

 How to use the continue statement in While loop

The continue statement is used to skip an iteration and move onto the next of the while loop. For instance, if we want to skip the number which is a multiple of 5 instead of just terminating the loop in the above example then we will use the continue statement: let i = 2; while (i < 21) { if (i % 5 == 0) { i+=2; continue; } console.log(i); i+=2;} As you can see that 5, 10 and 20 are missing because they are multiples of 5 as well as being even numbers.

 How to use the do while loop

The do while loop is built on top of the while loop meaning it is an extension of the while loop. In while loop the condition is evaluated before the execution of the loop’s body whereas the do while loop does the opposite and checks it after the execution of the body of the loop. runLoopAgain = true; while (runLoopAgain) { num = Math.random().toFixed(1)*10; if (num % 2 != 0) { runLoopAgain = false; } console.log(num);} In this example given above we had to declare and initialize the runLoopAgain variable before the body of the loop because the while loop evaluates the condition before the iteration. The do while loop checks the condition after every iteration, so If we are sure that we want to run the code present inside the loop at least one time then we use the do while loop. As we are sure in this example that we have to at least generate one random number before we check whether it is even or odd, a better way to write it would be: do { num = Math.random().toFixed(1)*10; console.log(num);} while (num % 2 == 0);

 How to use the for in, for of and foreach loops

The for in, for of and foreach loops are an extension of the for loop. Here we will discuss all of them; The for in loop is used to iterate over the properties of an object. Each iteration of the for in loop returns a key which can be used to access the value of the key: var employee = {firstName:"Mary", lastName:"Jane", age:33, id:092, department: "Education"};for (let p in employee) { console.log(p); console.log(employee[p]);} If the for in loop is applied to an array, it returns the index of each element. If we want to get the value present at each index then we can use the for of loop. var num = [5, 6, 7, 8, 9];for (let d of num) { console.log(d);} The for of loop is used to loop through iterable objects such as arrays, Maps, strings etc. If we use the for of loop on a string then it returns one character of the string each iteration: var greet = "Welcome to Linux Hint!";for (let c of greet) { console.log(c);} The .foreach() loop is used to perform a specific action on each element of the array; it loops through elements of the array and calls a function once for every element. The .foreach() loop takes a callback function as an argument which further takes three arguments, two of which are optional; The only required argument is the value of the current element. The index of the element and the whole array itself can be given as arguments to the callback function as well. Now we will look at an example where we have used the .foreach() loop to multiply each element of the array by two and print it to the console: var numbers= [99, 85, 788, 2, 255, 598]; numbers.forEach(function (value) { console.log(value +" * 2 = " + value*2);})

 Conclusion

Loops are control flow statements which are used to reduce code inefficiency and write more concise code. They are one of the most fundamental part of any major high level programming language. In this post we learned all about loops; we used JavaScript syntax to learn about for and while loops along with their extensions. Moreover, the break and continue statement for while loops were also discussed.

How to use the Fetch API

In web development you will often need to connect/communicate with other web servers to get information/data. For example, when signing up for a new account on some websites you will often see an option to sign up using your Gmail or other third party accounts. This enables you to sign up for a new account with just a single click instead of manually filling out the whole form. When you select the “sign up using a third party account” option then the application communicates with the third party application’s server and sends a request to access your information that is stored there. This request is sent through API which is a set of rules that govern how different applications or systems communicate with each other. In this article we will learn to use JavaScript to send such requests.

 What is the Fetch API

Fetch API provides a simple fetch() method which is used for fetching, accessing and manipulating resources across the network. The fetch() method allows you to make asynchronous JavaScript and XML (AJAX) calls with JavaScript which were previously made using XMLHttpRequest. The asynchronous requests run parallel to the main program and do not stop the execution of the code below them. The code below the Fetch API request will keep running even if the API has not sent any response back. When the API responds to the AJAX call then the fetch() method is resumed. Fetch API uses promises and provides powerful features which makes it much easier to handle web requests and their responses; it is a great way to avoid callback hells which were created when using XMLHttpRequest. Note: The browser console is used for the demonstration of examples in this article.

 The Syntax of Fetch API

We need to call the fetch() method in order to use the Fetch API in our JavaScript code. The fetch() method takes the URL of the API as an argument. fetch(URL) We need to define the then() method after the fetch() method: .then(function() {}) The returning value of the fetch() method is a promise. If that promise is resolved, the code present within the body of the then() method is executed. The body of the then() method should contain the code which can handle the data sent by the API. We then need to define the catch() method; the catch() method only executes in case the promise is rejected: .catch(function() {}); All in all the fetch() method should look something like this: fetch(url) .then(function() {}) .catch(function() {}); Now that we have an understanding of the syntax of Fetch API, we can now move on to the real world examples of using the fetch() method on a real API.

 How to use Fetch method to get Data from an API

In this example we will use a GitHub user’s API to get the user info data and display it on the console using only vanilla JavaScript; so let’s get started: First, we will create a variable called url; This variable will hold the URL of the API that will return the repos of a user named fabpot: const url = 'https://api.github.com/users/fabpot/repos'; Now we will use the fetch() method to call the GitHub User API; fetch(URL) The fetch() method takes the URL as an argument: fetch(url) .then(function(data) {})}) .catch(function(error) {}); In the code given above we have called the Fetch API to get the repositories of a user named fabpot from GitHub. We have passed the URL to the GitHub User API as an argument to Fetch API. The API then sends back a response which is an object with a series of methods; these methods can be used to perform different functions on the received information. If we want to convert the object into JSON then we can use the json() method. To convert the object into JSON we need to add the then() method. The then() method will contain a function; the function will take an argument called response: fetch(url) .then((response) => ) The response parameter is used to store the object which is returned from the API. this object is converted into JSON data using the json() method: fetch(url) .then((response) => response.json()) Now we can output the data in the form of JSON by adding another then() statement; this statement contains a function that takes a variable named data as an argument: .then(function(data) {})}) We then use the console.log() method inside the function’s body to output the data onto the console. .then(function(data) { console.log(data);}) Now we will add the catch() function to log the potential error to the console in case the promise is unfulfilled: .catch(err { console.error(err);}); All in all the request to get a list of user’s repositories from GitHub should look something like this: fetch(url) .then((response) => response.json()) .then((data) => { console.log(data);}) .catch(err { console.error(err);}); In the screenshot given above the promise was resolved and the body of the .then() method was executed. If the promise had remained unresolved due to some reason then the body of the .catch() method would have been executed which would do all the error handling. We have just used the .catch() method to print an error message in case the promise is unfulfilled.

 Conclusion

Communicating and Fetching data from third party sources is an essential part of web development. It was achieved by using a complex tool named XMLHttpRequest which caused callback hells; Now a much simpler tool called Fetch API is used to send AJAX calls in Vanilla JavaScript as it is much better at handling the AJAX requests. In this post we have learned to use the Fetch API method to make AJAX calls in vanilla JavaScript.

Download Top 10 JavaScript Books

JavaScript is a dynamically typed scripting language commonly used to engage the user by making interactive web pages. It adds dynamic elements to a static webpage that catch the user’s attention. A few years ago, JavaScript could only run on the client-side and was known as a client-side scripting language. JavaScript can now also be used on the server-side using environments such as Node.js. The JavaScript source code is executed in the client’s browser, and it can be processed without any communication with the server. Slideshows are a common example of an interactive element added by JavaScript to a website. There is a misconception that Java and JavaScript are the same languages. While Java may influence it, it has no direct relationship. Its syntax is closely related to that of C.

 Why should you learn JavaScript?

Every modern-day web developer needs to learn JavaScript as the leading programming language for web development. It is supported by every browser and can be used on both the client-side (scripting and animation) and server-side using third-party libraries like Nodejs and Reactjs. If you want to make modern dynamic websites, then knowing JavaScript is a must. You can use two different methods to learn JavaScript. You can either learn it by watching online tutorials or by reading books. Books are a lot more accurate, organized, and provide in-depth and detailed knowledge on a certain topic, but they require more focus and attention. If you do not have the time to read a book and watch quick tutorials, you should read this article about “Top 10 JavaScript Online Courses”.

 Top Ten JavaScript Books

Here’s a list of the top ten books to learn JavaScript

 1.Get Coding!: Learn HTML, CSS & JavaScript & Build a Website, App & Game

We’ll start our list with a children’s book called Get Coding!: Learn HTML, CSS & JavaScript & Build a Website, App & Game. Get Coding is a very beginner-friendly introduction to programming essentials. It not only teaches the basic concepts of JavaScript but also introduces kids to HTML and CSS. It enables young kids to build fun games, apps, and websites from scratch. It keeps the young ones engaged with funny illustrations and easy to understand language. It leads kids on an imaginary adventure to keep a precious diamond safe from dangerous thieves. Get This Book Now: Amazon

 2.Learn JavaScript Quickly: A Complete Beginner’s Guide to Learning JavaScript, Even If You’re New to Programming

The next entry on our list is another beginner-friendly book. It is written in clear, easy-to-understand language. It even has a full guide on the most basic programming concepts that all beginners should know before getting started with JavaScript. It also includes basic concepts of HTML and CSS and has straightforward instructions on how to build complex websites in a short amount of time. Get This Book Now: Amazon

 3.Learn JavaScript Visually: With Interactive Exercises

This book is visually appealing and full of illustrations. It teaches JavaScript through analogies, easy Interactive exercises, and metaphors. This book is suitable for slow learners who find long technical programming books boring and hard to understand. Get This Book Now: Amazon

 4.Head First JavaScript Programming: A Brain-Friendly Guide

This book also takes a visual approach to teach JavaScript. It is written in a very humorous and friendly tone. It starts from the most basic concepts and goes all the way to the advanced topics, but it mostly focuses on the basics of JavaScript. Get This Book Now: Amazon

 5.JavaScript & JQuery: Interactive Front-End Web Development

Jon Duckett writes JavaScript & JQuery, the top-selling book: HTML and CSS: Design and Build Websites. The first book also breaks topics into bite-sized chunks with a new topic on each page. Like Learn JavaScript Visually, the best thing about this book is that it is very colorful and engaging, unlike most books related to programming. It uses diagrams and photography to simplify complex and complicated topics. This book also introduces JQurey once the reader has a solid grasp of JavaScript. This book demonstrates how you can create sliders, content filters, and much more through examples. Get This Book Now: Amazon

 6. A Smarter Way to Learn JavaScript

This book is written especially to be easy to understand. The author tries to avoid unnecessary technical jargon to make the book easier to follow. The author used books to learn JavaScript; while learning JavaScript, he realized that the books written are poorly written. Then the author decided to write his own JavaScript book to make it very easy and clear to understand. The author, Mark Myers, has filled this book with exercises as he believes that one only remembers ten or twenty percent of what they read in a book. But this problem can be solved with exercises. When the reader completes a chapter, they can go to the author’s website and complete twenty interactive free exercises. The reader can keep trying to solve these exercises until they grasp the concept entirely. Get This Book Now: Amazon

 7.Eloquent JavaScript

This next entry on our list is Eloquent JavaScript. This book is for people who already have a thorough understanding of the basic concepts of programming. It features practice examples that are very hard and unintuitive. Get This Book Now: Amazon

 8.Speaking JavaScript: An In-Depth Guide for Programmers

This book is a quick and concise guide of JavaScript, written by a veteran programmer, Axel Rauschmayer. This book has four different sections:
    JavaScript quick start JavaScript in depth Background Tip, tools, and libraries
This book is also suitable for intermediate and above JavaScript developers as it provides clear and concise explanations rather than lengthy, in-depth ones. The examples and explanations after the introduction of a topic are kept to a bare minimum. Get This Book Now: Amazon

 9.JavaScript: The Definitive Guide

This book teaches about JavaScript and JavaScript APIs, which are implemented by web browsers and Node. It is suitable for learners who have some previous programming knowledge and readers who use JavaScript regularly but want to master the language. This book comprehensively explains JavaScript and provides a clear and comprehensive introduction to common front and back-end APIs available for JavaScript programs. As a result, it is a very long, dry, and detailed book. Get This Book Now: Amazon

 10. JavaScript: The Good Parts

The next entry on our list is JavaScript: The Good Parts. This book can be difficult to understand and is only intended for people who already know JavaScript. This book is small but quite dense and sometimes even feels like an academic paper, but once the reader gets through the dense material and grasps the book’s concepts entirely, they get immense knowledge on how to write good and efficient JavaScript code. This book simply cannot be overlooked but should only be read once a developer has a strong grip over the basic concepts of JavaScript. Get This Book Now: Amazon

 Conclusion

That concludes our list of top ten books for Javascript. There are many books out there for learning JavaScript, but the books listed here are the best of the best. Whether you’re a seasoned programmer looking to learn a new language or a beginner looking to enter the programming world, you can find the book suitable for you in the list given above. JavaScript beginners should opt for books like Get Coding!, Learn JavaScript Quickly, Head First JavaScript Programming, or A Smarter Way to Learn JavaScript. At the same time, those who already have the basic knowledge of JavaScript and want to enhance their knowledge further can opt for books like Eloquent JavaScript, Speaking JavScript, JavaScript: The Definitive Guide, or JavaScript: The Good Parts. Visual learners can read Learn JavaScript Visually or JavaScript & JQuery to learn about JavaScript. This list only includes the best among the best; Many other JavaScript books such as JavaScript for Kids and The Principles of Object-Oriented JavaScript can also be used to learn more about JavaScript.

How to Download JavaScript Libraries/Packages with NPM

Libraries contain pre-written code which a developer can integrate with their own code to perform different actions which would otherwise require them to write extensive, complex code. Packages can contain libraries, sub-packages, and other files. In some languages, libraries and packages are the same things.

 What is NPM?

NPM, short for Node Package Manager, is a package manager for node.js packages used to download and integrate packages into JavaScript code. These packages contain all the files which are required for a module (library). NPM is an integral part of the JavaScript ecosystem and contains many open source software, libraries, modules, or packages. It makes writing code a lot easier as developers can rely on already written code to perform different actions.

 How to Download NPM?

NPM comes with node.js; It automatically gets installed on your system when you install node.js. So we first need to install node.js from their official website: https://nodejs.org/en/download/ Visit the above-given link and download the LTS (Recommended) version of node.js. Once the download is complete, install node.js in your system. NPM will automatically get installed once node.js is successfully installed on your system. You can run the below-given command in the command prompt (cmd) to verify whether node.js and NPM have been properly installed on your system. > Node -v> Npm -v

 How to Download Packages using NPM?

Now we will download a package using NPM, which is a very straightforward process. To download any package using NPM, first open up the terminal, then use the following syntax: > npm install [package_name] In this example, we will install the Chalk package, which is used to style the text that gets displayed onto the console: > npm install chalk NPM creates a new folder by the name of (if it doesn’t already exist) “node_modules” to store the package. Now all your downloaded packages will be stored in this folder. To verify the successful installation of your package, run the below-given command: > ls node_modules

 How to Download Packages Globally with NPM

The method has given above only installs the NPM package locally; that means that the current project can only access the package. If you want to install an NPM package that any project on your system can access, then use the following syntax: > npm install -g [package_name] > npm install -g upper-case

 How to use the package

An NPM package can be integrated into JavaScript source-code in the following way: const upper_case = require('upper-case'); console.log(upper_case.upperCase("Hello Linux Hint!")); As most of you would most probably already know that Node.js is a server-side technology. So when we try to run the above-given code in a browser, it gives the following error: We can eliminate this error by installing any tool that will handle all the dependencies of the require() function in a browser. Here we will use a tool named Browserify. To install Browserify, run the following command: npm install -g browserify Now use the following command to make a file out of your source code where all the dependencies have been resolved: > browserify source-code_file-name.js -o bundle.js (You will have to run the above command each time you make any changes in the original source code) If you get an error by running the command as mentioned above, then open up the windows power shell and use the below-given commands before using the command given above: > Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted> Set-ExecutionPolicy RemoteSigned [These commands expose you to great security risks as they enable you to run unknown scripts on your system] Now run the command as mentioned above again; it should work this time. Now replace the script source from your source-code file’s name with bundle.js in the HTML file’ header and run the code again. The code will run properly this time and will not give any error.

 Conclusion

Libraries and packages contain sets of code that can be called upon by developers when building their own code. They perform actions that a developer might need in their own code. They are made to be integrated with someone else’s code and be used by others In this how-to guide, we have learned how to download, install and use packages using NPM. As NPM packages are a server-side technology, they need additional tools to run on browsers.

How to Use indexOf Method

indexOf() method is used to search for the index of an element in a given array; it can also be used to find the position of a character or a substring in a string. The indexOf() method returns the position of the element/substring if it is found; else, it returns -1. The indexing starts from 0, so the first element of an array and the first word in a string always return 0.

 How to use the indexOf() method

In this guide, we will learn how to use the indexOf() method to find the index of an element/substring in an array/string; but first, let’s discuss its syntax: array_name.indexOf(element, starting_point) string_name.indexOf(searchvalue, starting_point) The indexOf() method takes two parameters: element/searchvalue: The first parameter is required. It can be an element of an array or a substring of which the index is required. starting_point: This parameter is optional. It tells the method to start the search from the specified point. It is 0 by default. Now will use the indexOf() method to find the index of an element in an array as an example: Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 Examples

var animals = ['Lion', 'Monkey', 'Rhino', 'Cat']; console.log(animals.indexOf('Rhino')); Similarly, we can also use this method on a string: var str = 'Welcome to Linux Hint!'; console.log(str.indexOf('to')); It can also be used to find a single character: var str = 'Welcome to Linux Hint!'; console.log(str.indexOf('c')); The indexOf() method by default starts searching from 0; but we can pass the starting point as an argument as well: var animals = ['Lion', 'Monkey', 'Rhino', 'Cat']; console.log(animals.indexOf('Rhino', 3)); The method has returned -1 as it cannot find ‘Rhino’ if it starts the search from 3. Now, if we change the starting point to 2, then: var animals = ['Lion', 'Monkey', 'Rhino', 'Cat']; console.log(animals.indexOf('Rhino', 2)); Similarly for strings: var str = 'Welcome to Linux Hint!'; console.log(str.indexOf('c', 5)); var str = 'Welcome to Linux Hint!'; console.log(str.indexOf('c', 1)); The index() method starts searching from 0 to the end of an array/string; and returns the index of the first occurrence of the search value. If there are two similar items in an array or a string and you want to find the index of the last one, then you should use the lastIndexOf() method: var str = 'Welcome to Linux Hint!'; console.log(str.lastIndexOf('t')); Similarly for an array: var animals = ['Lion', 'Monkey', 'Rhino', 'Cat', 'Lion']; console.log(animals.lastIndexOf('Lion')); The indexOf() method is case-sensitive.

 Conclusion

While programming, when working with arrays or strings, we often need to find the index of a specific element or a substring. The indexOf() method comes in handy in such situations. In this how-to guide, we have learned how to use the indexOf() method to find the index of an item in a string/array. Moreover, we also discussed the type and parameters we can pass to the indexOf() method.

JavaScript Array Push and Pop Method

Arrays are crucial when working in any programming language to complete programming tasks. Arrays store the same data types, such as strings, integers, arrays, and even functions. When working with arrays, we frequently need to add or remove elements. The push() and pop() methods come to the rescue in this situation. In this post, we’ll go over what the push() and pop() functions are, as well as some examples to help you understand them better.

 What are push() and pop() methods

push() is used to add an element/item to the end of an array. The pop() function is used to delete the last element/item of the array. Let’s try to add and remove elements from an array using push() and pop() methods to understand these methods better. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use the pop() method

Suppose we have an array of numbers and we want to remove the last element from it. The code from removing an element from the end of the array would go like this: var intArr = [23, 45, 67]; intArr.pop(); // returns the removed item console.log(intArr);

 How to use the push() method

Similarly, if we want to add an element at the end of an array, the code for pushing or adding an element would go like this: var intArr = [23, 45]; intArr.push(67); // returns the new array length console.log(intArr);

 Conclusion

The pop() method removes an item from the end of an array, whereas the push() method adds an item to the end of an array. The returning value of the pop() method is the item that is removed from the array. The returning value of the push() method is the number of elements in the array after the new element has been added. These two methods are used a lot when working with arrays. In this post, we have had a thorough discussion on what pop() and push() methods are and how to use them.

JavaScript Array Length Property

While writing code, we might need to store multiple values. We can use a data type named array to meet this need. An array is a variable type in any programming language used to store multiple values of the same data type, such as a list of students or employees [Jane, John, Jack]. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 What is an array.length property

The array.length property is used to get the total number of elements in an array. For example, if we have the following array in our program: var students= ["John Doe", "Jane Doe", "John Smith"]; And we use the array.length property on it, then the array.length property will return a value of three as the array contains three elements. We can verify this by using the console.log() method. var students= ["John Doe", "Jane Doe", "John Smith"]; console.log(students.length) Now, if we add another element to the array and use the array.length property again, then the output on the console changes to: var students= ["John Doe", "Jane Doe", "John Smith", "Jacob Smith"]; console.log(students.length)

 How to set the number of elements in an array using the array.length method:

We can use the array.length property to set the number of elements in an array as well. Let’s take the array as mentioned above, “students,” as an example once again. It currently has 4 elements. We can use the array.length property to change the number of its elements. We will increase the number of elements from 4 to 5 in this example: var students= ["John Doe", "Jane Doe", "John Smith", "Jacob Smith"]; students.length = 5; console.log(students.length) The array.length property has added another element which is a non-iterable empty slot. We can verify this by outputting the whole array to the console: var students= ["John Doe", "Jane Doe", "John Smith", "Jacob Smith"]; students.length = 5; console.log(students.length) console.log(students) Now we will use the array.length property once again to reduce the number of elements from 5 to 3: var students= ["John Doe", "Jane Doe", "John Smith", "Jacob Smith"]; students.length = 5; console.log(students.length) console.log(students) students.length = 3; console.log(students.length) console.log(students) The maximum number of elements an array can have is 4294967295, as it is a 32-bit data type. As you can see in the example below, if we try to make an array of length4294967296, we will get an error. students.length = 4294967296; console.log(students.length)

 Conclusion

An array is a data structure consisting of a collection of elements that are used to store similar types of values. The array.length property is used to get or set the number of elements present in an array. If we use this property to get the number of array elements, it will give a number one higher than the highest index of the array; This is because of array indexing which starts at 0. In this how to guide, we have learned how to use the array.length property. This property really comes in handy when we have to run loops or conditionals on arrays.

JavaScript Array Shift and Unshift Method

When we work in any programming language, arrays play an essential role in fulfilling programming tasks., arrays store the same data types, like strings, integers, arrays, or even functions. While working with arrays, we often need to add or remove elements in an array. For fulfilling this need, shift() and unshift() methods come to the rescue. In this post, we will have a brief discussion about shift() and unshift() functions and a couple of examples to have a profound understanding of these functions.

 What are Shift() and Unshift() methods

The shift() method is used to remove an element/item from the starting point of an array. The unshift() method is used to add an element/item to the starting point of an array. Let’s try to add and remove elements from an array using shift() and unshift() methods to understand these methods better. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use shift() method

Suppose we have an array of numbers and we want to remove the first element from it. The code from removing an element from the beginning of the array would go like this: var intArr = [23, 45, 67]; intArr.shift(); // returns the removed item console.log(intArr);

 How to use unshift() method

Similarly, if we want to add an element at the start of an array, the code for adding an element would go like this: var intArr = [45, 67]; intArr.unshift(23); // returns the new array length console.log(intArr);

 Conclusion

The shift() method removes an item from the beginning of an array and shifts every other item to the previous index, whereas the unshift() method adds an item to the beginning of an array while shifting every other item to the next index. The returning value of the shift() method is the item that is removed from the array, and the unshift() method returns the new length of the array. These two methods are used a lot when working with arrays. In this post, we have discussed what shift() and unshift() methods are and how to use them.

JavaScript Arrays Tutorials – Explained with Examples for Beginners

While learning any programming language, we come across the learning of Arrays. Arrays come in helpful when there is a need to store several different values in a single variable. Arrays application is seen at many places, like implementing the matrices, data structures or storing data in tabular form. The concept of arrays came from the arrangement of objects in real life. The way we arrange objects in real life, we can arrange the data in programming. So this post is all about learning the core and basic concepts of Arrays. Let’s dive in and have a clear understanding of an array, how to create it, and use it to assign, access, and change values.

 What is an Array?

An array is a variable type in any programming language used to store multiple values simultaneously. Arrays store the data in the form of segments, also known as elements of the Array, so in simple words, an array is a collection of elements. We usually use them to store the same type of values or the list of items in one place/variable like the name of animals [“lion,” “bear,” “monkey”] or list of students [“John,” “Bob,” “Ivan”]. However, we can store multiple data types in arrays, like strings, integers, arrays, or even functions. The array types concerning implementation are divided into four types: Homogeneous arrays Heterogeneous arrays Multidimensional arrays Jagged arrays Let’s have a short introduction of each type.

 Homogeneous Array:

The Array in which the elements are of the same data type is known as a homogeneous array. For example, string, integers, or bool values. var stringArr = ["John", "Bob", "Ivan"];var intArr = [23, 45, 67];

 Heterogenous Array

The Array in which values of multiple data types are stored is known as heterogeneous Array. For example: var student = ["John", 25, "male"]

 Multidimensional Array:

The array which contains further arrays as elements in it is known as a multidimensional array. For example, list of students: var student = [["John", 25, "male"], ["Steve", 21, "male"], ["Angela", 22, "female"]]

 Jagged Array:

Jagged is almost the same as a multidimensional array but with a subtle difference in the number of elements in the sub-arrays within an array. The multidimensional Array in which the additional arrays datasets are not uniform. var student = [["John"], ["Steve", 21, "male"], ["Angela", "female"]] Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: use the F12 key in Chrome and other chromium-based browsers. use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to create an array?

Since JavaScript is a scripting language, we do not first have to declare the type and assign some values to a variable. We can directly write the variable’s name without mentioning the variable data type and assign values to it. For example: var languages = ["javascript", "python", "java"];

 How to assign values to an array?

Although we can assign values to an array while creating the Array, there is another way to assign values is by assigning values to specific indexes. The location where an item is present in an array is known as its index. For example: var languages = []; languages[0] = "JavaScript"; languages[1] = "Python"; Note: In arrays, index numbers start from “0”(zero):

 How to change the value of an array element?

The value of an element present in an Array can be changed the same way we can assign its values. For example, if we want to change the value of the first index of the “languages” array, the statement would go like this: languages[0] = "TypeScript";

 Built-in Array Properties and Methods:

The real perk of javascript is its built-in properties and methods for arrays. The most common array properties and methods present are:

 array.length property:

The “array.length” property can be used to get the number of items/elements present in an array. For example: var languages = ["javascript", "python", "java"]; console.log(languages.length);

 array.sort() method:

This Array.sort() method sorts the elements present in an array in ascending order. Suppose, we have an array of three programming languages: var languages = ["javascript", "python", "java"]; and we want to sort them out in alphabetical order so that the sort function will go like this: let sortedLang = languages.sort(); console.log(sortedLang); In the output, you can see the Array is sorted as we desired:

 How to access the elements/items of an Array?

Array elements can be accessed by mentioning the index number. For example, we want to access the second element of an array; the statement would go like this: let secondLanguage = languages[1]; Note: Array’s index number starts from zero“0”:

 How to access the first element/item of an array?

Since Array indexes start from “0,” so we can access the first element of an array by mentioning “0” in the square brackets as shown below: let firstLanguage = languages[0];

 How to access the last element/item of an array?

To get the last item of an array, the “array.length” property comes in help. We can access the last element present in an array by mentioning “array.length -1” in the square brackets as shown below: let lastLanguage = languages[languages.length - 1];

 How to loop through an Array?

To get all the elements present in an array, the best way is to loop through an array. The most convenient and efficient ways are to use: For loop array’s foreach method

 For loop:

To fetch all the elements using a for loop is the easiest way. Simply execute the code given below to loop through the whole Array and fetch all the elements one by one: var languages = ["javascript", "python", "java"];for (let i = 0; i < languages.length; i++) { const language = languages[i]; console.log(language);} In the above code, you can see that we used languages.length property in the conditional clause of for loop in order to loop through the whole Array without knowing the total number of elements in the Array.

 Array’s foreach method:

Javascript also provides the foreach method of the Array to loop through the whole Array. The syntax of using the foreach method is as follows: var languages = ["javascript", "python", "java"]; languages.forEach(oneLang);function oneLang(language){ console.log(language);} The above-provided syntax can be shortened using the inline callback function as given below: languages.forEach((language)=>{ console.log(language);})

 Associative arrays?

Associative arrays are the arrays that have named indices. JavaScript does not support such arrays. If you do so, javaScript will take it as an object, and the methods and properties of the Array won’t apply to it.

 Javascript Arrays are Objects:

Yes, the type of Array is Object. That’s why the arrays can hold different types of variables. Arrays can hold objects, functions, and even arrays within an array as an element. If we use the typeof operator over an array variable: var languages = ["javascript", "python", "java"]; console.log(typeof(languages)); It will show that the type of “languages” array variable is an object. However, there are still some conceptual differences between Arrays and Objects:

 Difference between Arrays and Objects:

In arrays, the indexes are denoted by numbers. While, in objects, the indexes can be denoted by names(numbers or alphabets). So, it is better to choose the right variable type at the right place: Use Arrays when you have a large list of items. Use Objects when you need to assign names to the indexes. Now, the question arises, how to identify whether a variable is an object or Array.

 How to identify an Array Variable?

For identifying, either a variable is an array or not, JavaScript provides an Array.isArray() function. For example: var languages = ["javascript", "python", "java"]; console.log(Array.isArray(languages)); The above code will return true. Note: The Array.isArray() function was introduced in ECMAScript 5.

 Conclusion

This post contains all the basic and necessary knowledge required for getting started with arrays. We first introduce What arrays are, then we learned how to create, assign, and change the values of an array. Moreover, we have learned some basic built-in properties and functions of arrays to get more interactive with arrays. In the end, we discussed the data type of Array and the difference between Arrays and Objects in detail.

What is JavaScript Console? Explained.

All major web browsers have developer tools built into them. This tool kit consists of the console, debugger, network activity analyzer, inspect element, etc., and makes web developers’ lives a lot easier. All modern browsers have a console that can be opened using a shortcut key from the keyboard. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”). It can also be opened by right-clicking on a web page and selecting the “Inspect” option from the menu. Now select the Console option to open the console:

 What is a console

Console is an object which is used to access the web console of the browser. It can be combined with different methods to perform several actions. Some browsers do not support specific methods. Google Chrome should be preferred over other browsers as it supports the most number of methods. Here is a list of some of the methods of the console object: console.log() To output logging information to the console console.info() To output informative information on the console console.error() To output an error on the console console.warn() To output a warning on the console console.clear() To clear the console console.time() & console.timeEnd() console.time starts a timer and console.timeEnd stops the specified timer and outputs the amount of time in milliseconds that has passed since it started console.timeLog() To output the value of a timer on the console console.table() To show data in tabular form on the console console.count() To output, the number of times a line of code has been executed under a given label console.countReset() To reset the value of the above mentioned counter console.group() & console.groupEnd() console.group to indent the following output by another level and console.groupEnd to exit the group. console.debug() To output a debug log level message console.dir() To output properties of a JavaScript object to the console Now we will use some of the methods mentioned above as examples.

 How to use console.log()

This is the most used console method to general output information to the console. It can take many arguments such as strings, variables, objects, arrays, functions, etc. console.log("Hello Linux Hint!"); In the same manner, console.info, console.error, and console.warn can also be used to output text on the console: console.info("Hello! This is Linux Hint."); console.error("This is an error message"); console.warn("This is a warning message");

 How to use console.table()

console.table is used to display data in tabular form on the console. It takes an array or an object as an argument: console.table({firstName:"Mary", lastName:"Jane", age:23, id:01});

 How to use console.group() & console.groupEnd()

It is used to indent the output to the next level: console.log("Before .group method"); console.group(); console.log("Within .group method"); console.groupEnd(); console.log("After .group method");

 How to use console.time() & console.timeEnd()

console.time() & console.timeEnd() are used to output the number of milliseconds a block of code or a function takes to be executed: console.time();for (let i = 0; i < 100000; i++) {} console.timeEnd();

 Conclusion

Many developers use the console to log information in order to figure out whether their code is working properly or not. It allows the developer to read, write and modify the JavaScript code while running in the browser. JavaScript has a built-in object named console that can be used to log information onto the browser’s console. In this guide, we talked about the built-in developer tools/console of the web browser. We also learned about the console object and its various options, and their functionalities.

JavaScript Date Formats

JavaScript has an inbuilt object called Date Object, which works with date and time in a platform-independent format; it represents the number of seconds passed since midnight of January 1970 by the ECMAScript standard. In this post, we will learn different methods to change the format of date; but to do that, first, we will need a variable to store the value of the date. JavaScript has an inbuilt data type (date object) that can be used to store dates. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: use the F12 key in Chrome and other chromium-based browsers. use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to create a Date Object?

In JavaScript, we can use the new Date() method to create a date object. var date = new Date(); console.log(date); The new Date() function without any parenthesis creates an object with the current date. We can also pass arguments to the new Date() function to create new date objects with specified date and time. Please see this article to know more about the Date Object and methods which we can use to operate on the date object.

 How to format the Date Object

In JavaScript, we have different methods which can be used to get the date in the required format. Here’s a list of a few of the methods that can be used to format the date object: toDateString() toTimeString() toISOString() toLocaleString()

 toDateString() method

We will start with the toDateString() method; The toDateString() method can be used to get the date in the following format:

 [ Day Month Date Year ]

var date = new Date(); console.log(date); console.log(date.toDateString()); This method is used to get only the date part from the whole date string.

 toTimeString() method

The toTimeString() method is used to get the time from the date string. It outputs the time in the following format:

 [ Hours:Minutes:Seconds Time Zone (Time Zone Name) ]

var date = new Date(); console.log(date); console.log(date.toTimeString());

 toISOString() method

This method is used to get the date in ISO format. This format gives the date in the zero UTC time zone. var date = new Date(); console.log(date); console.log(date.toISOString());

 toLocaleString() method

This method formats the date in a localized string format. This function takes a language and a country in standard locale code format, i.e., ‘en-US’ as a parameter, and formats the date according to the desired (specified) locale. var date = new Date(); console.log(date); console.log(date.toLocaleString('en-US'));

 The “get” methods

We can use the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() methods to output the date in our required format. The getFullYear() method can be used to get only the value of the year stored in the date object. Similarly, getMonth(), getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() can be used to get the individual values of Month, Date, Hours, Minutes, Seconds and Milliseconds respectively. We can combine any of these methods to get a date in our required format. In this example, we will format the date in the following way:

 Date/Month/Year

var date = new Date();var d = date.getDate();var m = date.getMonth();var y = date.getFullYear(); m++; console.log(d + "/" + m + "/" + y) In the above example, we increment the variable that contains the current month’s value because the months start at 0.

 Conclusion

Date formatting is an essential skill for web developers as they need to represent the date in a particular format. Many developers do not use the built-in JavaScript methods to operate on the date object as they can be very confusing. Instead, they use third-party libraries to manipulate the date object. In this write-up, we saw different methods which can be used to format the date object. All of these methods are present by default.

Beginners guide to classes

Classes are a template/blueprint for objects. They simplify the process of creating multiple objects with similar properties and methods. Classes were not present in ES5 and were introduced in the ES6 version of JavaScript. Classes are merely syntactic sugar, built on top of prototypes, and work in the same manner behind the scenes.

 How to use classes

Let’s take a programmer’s example who has to make five objects for five different users. He will write the following code: const user1 = { fName: "Mary" , lName: "Jane" , age: 23 , id: 01};const user2 = { fName: "John" , lName: "Doe" , age: 47 , id: 02};const user3 = { fName: "Jane" , lName: "Doe" , age: 34 , id: 03};const user4 = { fName: "John" , lName: "Smith" , age: 18 , id: 04};const user5 = { fName: "Mary" , lName: "Anne" , age: 22 , id: 05}; In the example above, the code has a lot of repetitiveness as all the objects have similar properties. We can easily eliminate the repetitiveness in code and make it more organized by using a class. In JavaScript, the class keyword is used to create a class. Classes use a method named constructor(). It automatically executes when creating a new object. It initializes the properties of the object. classUser { constructor(firstName, lastName, age, id) {this.fName = firstName;this.lName = lastName;this.age = age;this.id = id; } } In the example above, we have created a new class named User. It serves as a template/blueprint for all the user objects we want to make. The constructor takes four arguments and makes four properties for each object. These properties are named fName, lName, age, and id and can be accessed by using the following syntax (after we have created the object) object_name.property_name The ‘this’ keyword in the example refers to the object that owns the age property. This keyword is used to access the value of a property within an object. Now we will create the user objects shown in the first example using the User class. classUser { constructor(firstName, lastName, age, id) {this.fName = firstName;this.lName = lastName;this.age = age;this.id = id; } }const user1 = newUser('Mary', 'Jane', 23, 01);const user2 = new User('John', 'Doe', 47, 02);const user3 = new User('Jane', 'Doe', 34, 03);const user4 = new User('John', 'Smith', 18, 04);const user5 = new User('Mary', 'Anne', 22, 05); Here you can see that the code has become a lot more readable.

 What are methods classes

We can also add methods to classes. These methods can be easily added to the body of the class after the constructor by using the same syntax which is used in objects: classUser { constructor(firstName, lastName, age, id) {this.fName = firstName;this.lName = lastName;this.age = age;this.id = id; } birthYear() {const date = newDate(); let Year = date.getFullYear() - this.age;return Year; } }const user1 = new User('Mary', 'Jane', 23, 01);const user2 = new User('John', 'Doe', 47, 02);const user3 = new User('Jane', 'Doe', 34, 03);const user4 = new User('John', 'Smith', 18, 04);const user5 = new User('Mary', 'Anne', 22, 05); Now, if we try to access the birthYear() method and print it on the console using the console.log() method, then we will get the following output: console.log(user1.birthYear()); console.log(user2.birthYear()); console.log(user3.birthYear()); console.log(user4.birthYear()); console.log(user5.birthYear());</td>

 How to use the Getter and Setter methods

The Getter and Setter methods can be used in a class to get and set the value of a property in an object. Use the get or set keyword to use the getter or setter method, respectively: classUser { constructor(firstName, lastName, age, id) {this.fName = firstName;this.lName = lastName;this.age = age;this.id = id; } get userAge() { returnthis.age; } set userAge(i) {this.age = i; } }const user1 = new User('Mary', 'Jane', 23, 01); console.log(user1.age); // will output 23// setting the value of the age property user1.userAge = 24; console.log(user1.age); // will output 24

 Conclusion

Classes are code templates that are used to create new objects with similar properties and methods. They come in handy when the coder has to make several different objects with similar properties. In this write-up, we have discussed classes. We learned how to use them to create objects. Moreover, we also learned to add different methods to objects using classes.

JavaScript Date Object – Explained

JavaScript has a built-in datatype that creates dynamic dates or stores current, previous, or future dates. Date objects can be created by using the new Date() method. Once the date object is created, you can apply different operations to it. You can show a timer on your website using the date object. The date is the number of milliseconds passed since the midnight of January 1, 1970, UTC. It is important to note that although the date is based on UTC when the JavaScript code is executed on a browser, it fetches the time zone from the host system: Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to create a Date Object?

As mentioned above, a date object can be created with the new Date() method. To use a date object, we first need to create a variable and then store its date. The date is displayed as a full-text string. var date = new Date(); console.log(date); The new Date() function without any parenthesis creates an object with the current date. We can also pass arguments to the new Date() function to create new date objects with any specified date and time. The arguments use the following syntax in the new Date() function: new Date(year, month, day, hours, minutes, seconds, milliseconds) Example: var date = new Date(2001, 10, 10, 01, 37, 50, 50); console.log(date); In the above example, the 10th month is November; this is because JavaScript starts counting months from 0. So January is the 0th month. We can pass (minimum) 1 to (maximum) 7 arguments to the new Date() function. Now let’s try with five parameters: new Date(year, month, day, hours, minutes) var date = new Date(2001, 10, 10, 01, 37); console.log(date); The seconds are 00 by default. In the same way, we can also give two, three, four, and six arguments. The order of the arguments will always remain the same unless we are only giving a single argument. If only one parameter is supplied to the new Date() function, it will be considered as milliseconds: var date = new Date(2001); console.log(date); The time shown in the screenshot above is 2001 milliseconds past midnight of January 01, 1970. One or two-digit years will be considered from the previous century: var date = new Date(9, 5); console.log(date); We can also pass a date string to the new Date() function: var date = new Date("November 10, 2001 01:37:50:50"); console.log(date);

 JavaScript Date Methods:

In JavaScript, we can use different methods to perform different actions on a date object. A few of these methods are discussed here:

 The getFullYear() method:

The getFullYear() method can be used to get the year from the date object. var date = new Date(); console.log(date.getFullYear());

 The getMonth() method:

The getMonth() method returns the value of the month in the date object. var date = new Date(); console.log(date.getMonth()); Note: This value is always one less than the actual month. Similarly the getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() can be used to get the individual values of Date, Hours, Minutes, Seconds and Milliseconds respectively.

 The getTime() method:

The getTime method can be used to get the number of milliseconds that have passed since midnight Jan 1, 1970: var date = new Date(); console.log(date.getTime());

 The getDay() method:

The getDay() method is used to get the number of the weekdays in the date object. Days are numbered from 0 to 6, and the week starts from Sunday. var date = new Date(); console.log(date.getDay());

 The setFullYear() method:

The setFullYear() method is used to set the year of the date object. It can optionally set the month and the day of the date object as well. var date = new Date(); console.log(date.getFullYear()); date.setFullYear(1993); console.log(date.getFullYear());

 The setMonth() method:

The setMonth() method is used to set the month in the date object. var date = new Date(); console.log(date.getMonth()); date.setMonth(8); console.log(date.getMonth()); Similarly the setDate(), setHours(), setMinutes(), setSeconds() and setMilliseconds() can be used to set the individual values of Date, Hours, Minutes, Seconds and Milliseconds (respectively) in the date object.

 The setTime() method:

The setTime method can be used to set time in milliseconds after midnight of Jan 01, 1970. var date = new Date(); console.log(date); date.setTime(800000); console.log(date);

 Conclusion

Date object is an inbuilt data type that is used to store and display dates. Whenever you see a time counter or a countdown on a webpage, there is a date object behind it. Date objects are extremely useful when working with dates. In this post, we discussed what a date object is and how to create it. Moreover, we also learned some methods which we can use to operate on a date object and manipulate it according to our needs. Date objects can be very confusing and difficult to work with. Many JavaScript developers opt for third-party libraries instead of the inbuilt date object when they need to use dates in their code.

JavaScript Array Filter Function

Javascript provides many built-in array functions for getting tasks done quickly and in an efficient way. Javascript filter() function is one of those popular functions used to iterate over an array’s elements and get the desired result. In this post, we will grasp the concept of the javascript filter() function. What is a filter() function, and how can we use it to help in simplifying the Javascript code and complete the tasks efficiently and most quickly.

 What is the filter function

Javascript’s filter() function for the array is used to filter out the data based on the given condition or test. The filter() function takes the element of an array one by one and applies the condition on each element. The filter() function keeps the elements that pass the condition in a different array and return the resulting array after iterating through the whole array. This filter() function of the array does not affect the original array. Let’s explore more into it to understand the syntax and its functionality, along with a couple of examples.

 Syntax of filter function

array.filter(function_name, thisValue); Array’s filter() function takes a function as a callback function with three arguments. The syntax of the callback function and the sequence of arguments will go like this: function function_name(value, index, array) { return condition;} In the call back function of filter() method: The first parameter is the current value of the array element during the iteration. The second parameter is the optional parameter which is the current index of the array element during the iteration. Lastly, we can also pass the array itself to the callback function for having some custom functionalities inside the callback function. We can also pass “thisValue” to the function, where the “this” keyword refers to the parent block/object. Now we will use a couple of examples to see its real-life implementations. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use filter() function

The best example to understand the filter() function is to filter some numbers from an array of numbers based on the given condition.

 Example 1:

Suppose we have an array of numbers and we want to get numbers greater than some specific number: var numbers = [23,16,38,5,10,19] The first method to get the desired range of numbers is to loop through the whole array and put a condition inside the loop to check whether the number passes the given test (greater than 18 or not). If the number passes the test, it will be added/appended to a new array. The code of the for loop for filtering out the numbers is given below: varfilteredArray = [];for (leti = 0; i18) { filteredArray.push(numbers[i]) }} console.log(filteredArray); In the above code, we first put a loop over the “numbers” array, then put a condition using the if statement, and if the array element passes the condition, it will be appended/pushed to the “filteredArray” variable. Although we have got the desired range as output. But, why not use a smart and easy way to get the filtered Array using the filter() method of the array, where we do not have to mutate the variables like “filteredArray.”

 Use of filter() function

The filter() function to get the numbers greater than 18 will go like this: varfilteredArray = numbers.filter(getAdults); functiongetAdults(n){ return n >18;} console.log(filteredArray); In the above-given code, you can see that we have first passed the “getAdults” function to the filter() function, and in the “getAdults” function definition, we just checked whether the number is greater than 18 or not and if this condition returns true then return that array element. Once the “filter” function checks all the numbers in the “numbers” array, it will store the final result in the “filteredArray” variable. Lastly, we have just consoled the “filteredArray” variable to verify whether our filter() function worked fine or not. You can verify by looking in the screenshot provided above that the filter() function has returned all the numbers which are greater than 18. Another shorter and easier way to write filter() function is to make the callback function of filter() function an arrow function: The syntax of writing the callback function within the filter() function’s parentheses will be like this: varfilteredArray = numbers.filter((n) => {return n >18}); console.log(filteredArray); Alright, this was the simple example in which we have an array of numbers only; what about the array of objects. Let’s try that one as well.

 Example 2:

Suppose we have a list of students in an array, and we want to get the list of the students whose fees are above $8000: var students = [ { id: 1, name: "John," age: 12, fee: 8500 }, { id: 2, name: "Bob", age: 15, fee: 4500 }, { id: 3, name: "Steve", age: 10, fee: 7500 },{ id: 4, name: "Harry", age: 13, fee: 10500 }, { id: 5, name: "Tom", age: 14, fee: 9000 }, { id: 6, name: "Ron", age: 11, fee: 6000 },] The filter() function to get the filtered list of students will go like this: varfilteredStudents = students.filter((student) => { returnstudent.fee> 8000}); console.log(filteredStudents); Now, the only difference in this code is that a single object is passed as a value to the callback function, and inside the definition of the callback function, we put a condition and return the object where the student’s fee is greater than $8000. By looking at the screenshot attached above, you can see that students’ fees are greater than $8000 and are displayed as an output. So this is how we can access the objects of an array in the filter() function.

 Conclusion

In this post, we have learned what a filter() function is and how we can use it to help in simplifying the Javascript code. We have learned that the filter() function filters out the array elements based on the given condition. The filter() function takes the element of an array one-by-one, takes a callback function applied to every element of the array, and returns the new filtered array. This post is all about JavaScript’s filter() function and its usage. It contains some basic examples that help in understanding filter() function easily.

Top 10 JavaScript Online Courses

JavaScript is a scripting language widely used across the internet to enhance the user experience by adding interactive and dynamic elements to a webpage. It converts static pages (made by CSS & HTML) into dynamic ones that catch the user’s attention. JavaScript can run without communicating with the server as the client-side’s source code is processed by the client’s browser. Slideshows, change in the colour of a button when the cursor hovers over it, displays of a time countdown are common examples of interactive elements added by JavaScript to a website. Some People have a misconception that Java and JavaScript are similar. There is no similarity between them other than their names.

 Why learn JavaScript?

JavaScript is a wildly popular programming language among professional developers. It is powerful and versatile yet very easy to get started with. It is used on both the front end (animations, slideshows) and the back end. Just a few years ago, JavaScript was only a front-end/client-side scripting language. But now, it can also be used on the back end/server-side of a website using environments like Node.js. JavaScript source code can run on any modern browser.

 Top Ten JavaScript Online Courses for Beginners and Experts:

Here’s a list of the top ten online courses:

 1.The Complete JavaScript Course 2021: From Zero to Expert!

This course will help you become an expert JavaScript developer from scratch. By taking this course, you’ll understand the behind-the-scenes working of JavaScript. It introduces all the JavaScript fundamentals, i.e., variables, conditionals, operators, boolean logic, arrays, functions, objects, strings, loops, etc. This course includes 50+ challenges and assignments for the readers, which helps them polish their skills. This course is long and may become boring for you if you only want to get a basic introduction to JavaScript. The course introduces complex topics like APIs, higher-order functions, event loops, ‘this’ keyword, etc. This course does not require you to have any coding experience as it is very beginner-friendly.

 2.JavaScript: Understanding the Weird Parts

This course also lets you know how JavaScript works behind the scenes and how it differs from other programming languages. This course is for developers who already know the basics of JavaScript. It included advanced topics such as prototypal inheritance, closures, etc. This course helps you learn how to debug JavaScript. It also introduces you to the source code of JavaScript frameworks and enables you to build your own libraries and frameworks. This course requires you already to know the fundamental programming concepts like loops and variables. It also requires the learner to know a bit of JavaScript as well.

 3. Modern JavaScript From The Beginning

This course teaches you JavaScript without using any third-party frameworks or libraries. It is suitable for more experienced developers as it bombards the learner with a lot of new information. The course expects you to know HTML and CSS already. The course uses 10 project examples to teach you about document object model, ajax, fetch API, JavaScript patterns, error handling, etc., with pure vanilla JavaScript.

 4.JavaScript – The Complete Guide 2021 (Beginner + Advanced)

This course takes you from being a beginner to an expert JavaScript developer. It introduces you to all the modern JavaScript development features and concepts. This course also focuses on project-driven learning. It teaches you about fundamental programming concepts like variables and functions along with OOP. Then it moves onto more advanced topics such as Manipulating web pages using JavaScript, asynchronous coding, metaprogramming, event handling, and how JavaScript works under the hood. The course does not require you to have any JavaScript knowledge. You don’t even need web development knowledge to start this course, but it is recommended to know the basics.

 5.Learn JavaScript with Codecademy

Codecademy is an interactive platform that helps you learn 12 different programming languages such as JavaScript, Python, etc. Codecademy also offers a ‘pro’ version that gives learners access to quizzes, more realistic projects, and personalized learning plans. Codecademy is the best option for you if you do not know anything about JavaScript. It teaches the basic and most fundamental topics using the latest JavaScript syntax.

 6.The Modern JavaScript Bootcamp

You do not need any programming experience to start this course. The course starts from the very basic JavaScript and takes you through the latest features of ES6 and ES7 by building three web applications. It also enables you to put your skills to the test by solving 80+ coding problems. You will learn about promises and asynchronous JavaScript and fix your code by debugging it. You will also get an 80 page PDF guide with lecture notes, coding examples, and links to documentation.

 7.50 Projects In 50 Days – HTML, CSS & JavaScript

This project is amazing once you already know the basics of JavaScript, as it helps you take your front-end development skills to the next level… The instructors will not explain every new thing/syntax they use in the course. This course takes the project-based approach to teach front-end development. It enables the learner to build amazing and unique projects using CSS animation, custom properties, and modern styling.

 8.20 Web Projects With Vanilla JavaScript

This course also takes a project-based approach to teach JavaScript. You learn it by doing it. The learner will build 20 projects from scratch without using any JavaScript or CSS framework. The learner will also learn to fetch third-party APIs and JSON into their code. It teaches the learner about DOM manipulation, fetches, promises, arrows, events, etc. This course is beginners friendly but does require you to have basic knowledge of web development.

 9.JavaScript & jQuery – Certification Course for Beginners

This course also introduces jQuery along with JavaScript. So if you want to learn jQuery along with JavaScript, then this course is right for you. This course introduces the learner to Variables, Assignment & Arithmetic Operations, Data Types & Objects, Arrays, Array Attributes, Array Splicing, Loops, Functions & Events, Stop, Callback Functions, Chaining, Draggables, Accordion Menus, and so much more.

 10. The Web Developer Bootcamp 2021

This complete and comprehensive web development course will make you an expert, HTML, and CSS. You will build responsive, accessible web applications with beautiful layouts using the latest technology. It will take you from the beginner level to the expert level, where you will be able to install all the required packages using NPM, create node modules, master the CLI and implement user authentication along with much more.

 Conclusion

So that concludes the list of the top 10 best online courses for Javascript. All of these courses are the best among the best and are top-rated by the learners. The list above contains courses for all levels of expertise. It doesn’t matter whether you’re a beginner or an expert, you can find the course suitable for you from the list given above. You can choose any course that is suitable for your level of expertise. From the courses above, beginners can choose The Complete JavaScript Course 2021, JavaScript – The Complete Guide 2021 (Beginner + Advanced), Learn JavaScript with Codecademy, The Modern JavaScript Bootcamp, or The Web Developer Bootcamp 2021. On the other hand, the more experienced developers can opt for JavaScript: Understanding the Weird Parts or 50 Projects In 50 Days – HTML, CSS & JavaScript.

Top 5 JavaScript Online Code Editors

Online code editors allow you to start writing code without any setup. These code editors can be accessed from anywhere, anytime. Most of them are free and have collaboration features that allow remote team members to contribute to a project easily. Some of these online tools only have basic features, while others are full-fledged IDEs.

 Difference between Compilers and Interpreters/Code Editors:

Compilers and interpreters are software used to convert source code into machine code that computers can understand. Interpreters convert one line at a time while the compilers translate the entire source code simultaneously. Compilers are used by programming languages such as C, C++, Java, etc., while interpreters use programming languages such as JavaScript, Ruby, and Python. In this post, we will discuss the top five code editors/ interpreters for JavaScript available online. So let’s begin:

 1.StackBlitz

This IDE is quite similar to the VSCode editor, so if you are familiar with VSCode, you should go for StackBlitz when using an online code editor. It is fast, secure, and has IntelliSense. StackBlitz allows you to import any NPM package. The code editor takes care of dependencies, hot reloading, and compiling automatically while you type. This editor also gives you the option to do offline editing. Moreover, you can Drag & Drop files and folders into the editor. All applications on StackBlitz get automatically deployed on their server. While using StackBlitz, you can share your projects with just one click. It has support for five different workspaces: JavaScript React AngularJS Ignite UI KendoReact

 2.CodePen

CodePen is an open-source online code editor which is used to test and showcase user-created front-end code. CodePen allows you to see other people’s projects and understand how the code is actually working. CodePen gives you all the tools that are required for collaboration, experimentation, and sharing your code. You can just start coding without any setup.

 3.JS Fiddle

JS Fiddle is super easy to use and has a very user-friendly and intuitive UI. JS FIddle wasn’t made to be a full-fledged web development environment. This code editor is only for prototyping, making demos, live code collaborations, bug reporting for GitHub issues, and presenting code answers on Stack Overflow.

 4.Code Sandbox

Code sandbox is optimized for frameworks such as Vue, React, Angular, and so many more. It is integrated with Github, which enables you to export or import repos from Github directly. Like StackBlitz, Code Sandbox also allows you to use any public npm packages. Code Sandbox features live collaboration along with VSCode integration.

 5.AWS Cloud9

Cloud9 is a cloud-based IDE built by Amazon Web Services, which supports multiple programming languages such as JavaScript with Node.js, C, C++, PHP, Ruby, Python, etc. Cloud9 provides all the tools that are necessary to develop large-scale software. It is very straightforward and can be easily integrated into the AWS ecosystem. It allows you to work from anywhere, which increases productivity.

 Conclusion

That concludes our list of the top 5 online code editors. Online IDEs and code editors are easy to use and offer accessibility. You do not need to spend any time setting up your IDE. You can just go to the web-based IDE and start coding from anywhere on any device. In this write-up, we have listed the top 5 online code editors. There are many other web-based code editors available there, but these are the best of the best.

Top 5 JavaScript Code Editors and IDEs

Code editors are text editor programs specifically designed to write and edit source code of a software while IDEs (integrated development environments) provide tools and facilities required for software development; IDEs consist of code editors debuggers and build automation tools. They provide a single environment where everything can be done, from writing to executing the code. This increases the productivity of the developers and makes their lives easier. In this post, we will discuss the top five code editors/ IDEs for JavaScript. Let’s begin

 1.Visual Studio Code

The first one on our list is Visual Studio Code; this IDE does not need any introduction. It is the most popular and reliable integrated development environment for JavaScript. This IDE is available across all major operating systems. Its features include IntelliSense, code refactoring, debugging tools, function in-line peak, and much more. It is integrated with github which allows you to run commands like push, pull and commit. VS Code also allows you to add additional features to your IDE by installing plugins. It is light, highly customizable, and completely free. Download form here

 2. Atom

Atom is a very popular, free-of-cost, open-source, cross-platform source code editor for JavaScript. Unlike Visual Studio Code, the atom is just a code editor and does not feature code execution. Atom is built on top of the electron, a framework used to build cross-platform desktop apps. It includes features such as completion of code and easy integration with github. You can customize Atom by adding additional plugins and packages to it. Atom features a real-time collaboration option. Download form here

 3.Sublime Text

Like Atom, Sublime Text is also a code editor for JavaScript, which does not feature code execution. However, unlike Atom, it is not free; it does offer an evaluation period after which the user has to purchase the license keys for $99 (as of now). It has an incredible user interface that is very intuitive. Sublime Text is powerful, flexible, and lightning-fast, unlike many other resource-hungry software. Download form here

 4. Web Storm

Webstorm is another popular IDE available for JavaScript. It has an evaluation period of 30 days, after which you have to buy it for $5.90 per month for individual use. It has tons of features and tools like refactoring, quick documentation, error compilation, built-in HTTP client, and many other integrated tools. It also has an inbuilt debugger which helps in error identification. Download form here

 5.Komodo Edit

Komodo Edit is the free version of the paid Komodo IDE; it is simplified and lacks some of the features present in the paid version, but it still is a very powerful IDE. It allows you to work across platforms with different languages and frameworks. It offers features such as Auto-Complete & Calltips, Projects & Places Manager, Minimap, etc. It allows you to track changes in your code. Download form here

 Conclusion

Choosing the right development environment is essential if you want to write efficient code. Good IDEs and Code Editors help a developer save time and boost their performance. Many other great IDEs and code editors are also available, which could not make it to this list. These include Sublime Text 3, IntelliJ IDEA, RJ TextEd, etc. In this write-up, we have listed the best code editors and IDEs available for JavaScript. Every Code Editor and IDE has its own pros and cons. So the decision of choosing the right development environment for your project should come down to the requirements of your project.

What is the typeof Operator?

The typeof is an operator present in most programming languages and is used to check the datatype of an operand (opernad: the variable which is operated on). In this write-up, we will learn all about the typeof operator, what it is and how to use it; but first, we need to understand what data types are.

 What are data types:

Data types are a classification of data that defines how data can be stored and manipulated. Each programming language has built-in data types which might be different from other programming languages. Here’s a list of the six most basic data types: Number: As the name implies, it consists of numbers Boolean: Booleans can have only two different values; true or false. String: Strings are a collection of alphanumeric characters. Undefined: Empty or undeclared variable. Object: Bundle/Collection of Data The typeof is not a function, but rather it is an operator. In programming languages, functions and operators are different; they may behave similarly but are synthetically and semantically different.

 How to use typeof operator:

A variable is passed to the typeof operator as a parameter and returns the variable’s datatype.

 Syntax

typeof (var) typeofvar Both of the syntaxes mentioned above are correct. The operand can be written with or without parentheses. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing + , and in the Advanced tab, check “Show Develop menu in menu bar”).

 Examples:

Now we will look at a few examples of typeof operators. The typeof operator is present in many programming languages, but we will use the JavaScript syntax for these examples. In the code given below, we have declared a variable named age and assigned it a value of 10. Then we used the typeof operator to determine the datatype of age. The typeof operator was put inside console.log() to output the return value of the typeof operator on the console. var age = 10; console.log(typeof(age)); If we assign a new value to age, i.e., ten instead of 10, then the output changes to: var age = 'ten'; console.log(typeof(age)); Now, if we do not assign any value to age and use the typeof operator on it; then the operator will return the following value: var age; console.log(typeof(age)); We can use the same method to determine other data types as well like boolean, object and symbol, etc.: var x = true; console.log(typeof(x)); As you have already seen in the above examples, the typeof operator can be combined with other functions and methods such as conolse.log. It can also be combined with conditionals, loops, etc. In the example given below, the typeof operator is used with conditional statements: var age = 5;if (typeof(age) == 'number') { console.log('The provided number is in the form of digits.') }else{ console.log('The provided number is not in the form of digits.')} Now, if we change the age from 5 to five, then the output changes to:

 Conclusion

The typeof operator returns the datatype of the operand (the variable which is passed as the parameter to the operator). It is very helpful in programming languages such as JavaScript as it has dynamic data types. Dynamic data type means that the same variable can store different data types within a single program. In this write-up, we have learned what data types are and an operator in programming languages. Moreover, we have also learned about the typeof operator and how to use it using JavaScript syntax.

JavaScript For Loop – Tutorial for Beginners

In programming languages, loops are used to run a block of code repeatedly until a specific condition is satisfied. All major programming languages, including JavaScript, contain the concept of loops. JavaScript is a text-based scripting language commonly used to add dynamic and interactive elements to static websites to make them visually appealing. Loops have different syntax in each programming language, but the basic concept (logic) remains the same. Most programming languages have more than one type of loop. The famous are for and while loop. This guide will only learn about the loop and where it should be used instead of other loops (favored over other loops). Loops can be interchanged with each other in most cases, but loops should be used when you have to run a determinate number of iterations (when you already know the number of times the loop will run).

 For Loop Syntax:

First, we should discuss the syntax for loop uses: for (initialization; condition; **variable value modifier statement**) { Code to be executed} In for loop: First, initialize/set a variable(initialization runs before the execution of the body) i.e. let i=0; Secondly, define the condition for the loop(this statement runs before the execution and decides whether the loop will run or not), i.e., i <= 10; Lastly, The third and the last statement runs after the body of the loop is executed. It modifies the value of the variable for the next iteration, i.e i++ or i– Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use for loop?

We will take a programmer as an example who has to output a sequence of numbers from one to twenty using JavaScript. They will have to write twenty lines of code to output this sequence. This way of writing code is very inefficient. We can efficiently write such repetitive tasks using loops. As mentioned above, the number of lines in the program can be reduced from twenty to four using a for a loop. for (let number = 1; number <= 20; number++) { console.log(number);} Now let’s discuss how a for loop actually works. The first statement, i.e., initialization, runs before the statements present inside the body of the loop and sets a variable. The second statement also runs before the execution of the block of code. It defined the condition for the loop. This statement decides whether the loop will run for the next iteration or stop at the current iteration. The third and the last statement runs after the statements inside the loop are executed. It is incrementing the value present inside the variable. We can also decrement the value of a variable in a loop. Now we will output the sequence from twenty to one in descending order: for (let number = 20; number >0; number--) { console.log(number);}

 What is for/in the loop?

The for/in loops are used to loop through the properties present inside an object. It comes in handy when you have to run a loop through an object but don’t know the number of properties present in the object. Syntax: for (varin object) { Statements} Here var is used to store a different property name in each iteration. The loop runs through the properties of the specified object. var employee = {fname:"John", lname:"Doe", age:20, Id:001, Department: "Health & Safety"};for (let prop in employee) { console.log(prop);}

 What is for/of the loop?

The for/of loops are used to loop through the values of an array. var names= ['John Smith', 'John Doe', 'Jane Doe'];for (let value of names) { console.log(value);} for/of loops can also be used to run through the values of a string.

 Conclusion

Loops are used to write concise and efficient code. They eliminate repetitiveness from code. They are a fundamental part of any major programming language. As mentioned above, for loops, take three arguments. The first argument/parameter is the initializer that sets the variable. The second argument is the condition; The loop will continue running until that condition becomes false. The third and the last argument is used to modify the variable which was set in the first argument. All of these three arguments are optional. These three arguments should always be specified despite them being optional. Failing to give arguments to a loop can create an infinite loop that can cause a crash program. The for loops are generally used when the coder knows the number of times the loop will run. In this how to guide, we learned to use for loops using JavaScript syntax. We have also learned about for/in and /of loops.

JavaScript forEach Loop

The forEach loop is a special type of loop present in most programming languages used to loop through the elements of an array. It is mostly used to replace the loop to avoid potential off-by-one bugs/errors as it does not have a counter.

 Why should we use a forEach loop

To use a for loop, we need to define the number of times the loop will run, unlike forEach loop, which does not need any counter. When we use a forEach loop, we essentially say “do this to every element of this collection” whereas, in the loop, we explicitly state the number of times the loop will run. This can cause errors and make the code extremely difficult to read as array indexing starts at 0. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 Syntax of forEach loop

array.forEach(function(value, index, arr), thisValue) Replace the array with the actual name of your array. Parameters: value: Required; Stores the value of the current element. Index: Optional; Stores the index of the current element of the array. arr: Optional; Holds the array object that contains the current element. thisValue: Optional; This parameter is used as this value of the function. undefined is used as the default this value if this parameter is not given. undefined is the return value of forEach method.

 How to use a forEach loop in JavaScrip

Now we will use the forEach loop to output each element of an array named numbers on the console as an example: var numbers= [1, 2, 3, 4, 5, 6]; numbers.forEach(function (value){ console.log(value) ;}) In the example given above, first, we declared an array named numbers and assigned it six elements. Then we used the forEach loop to loop through each item present in the array. We then declared and defined a function inside the forEach loop that prints the element’s value in the current iteration of the loop onto the console. We can also declare and define the function outside of the loop and just call the function from the body of the loop: var numbers= [1, 2, 3, 4, 5, 6]; numbers.forEach(pr); function pr(value){ console.log(value);} The forEach loop is not executed for the empty elements of the array. If we add another element to the array as mentioned above by using the array.length property and run the program again, the output will remain the same: var numbers= [1, 2, 3, 4, 5, 6]; numbers.length = 7; console.log("The Length of the array is " + numbers.length); numbers.forEach(pr); function pr(value){ console.log(value);} Now we will try to perform different actions on the elements of the array. First, let’s try to write a function that prints the square of each element of the array on the console: var numbers= [1, 2, 3, 4, 5, 6]; numbers.forEach(pr); function pr(value){ let square = value * value; console.log(square);} Now let’s try to output the sum of all the elements of the array to the console: var numbers= [1, 2, 3, 4, 5, 6]; let sum = 0; numbers.forEach(pr); function pr(value){ sum = sum + value;} console.log(sum);

 Conclusion

The forEach loop is a control flow statement that is used to loop through items in a collection. It proves useful when we need to perform different actions on each element of the loop individually. In this post, we took up the forEach loop. We learned what it is and how to use it. Moreover, we also compared it with the more common for a loop.

JavaScript Functions – Explained with Examples for Beginners

While coding, we might need to perform a certain action multiple times, e.g., two numbers. We can either do it repetitively in the program or just make a function that takes two numbers as an input, adds them, and returns the answer. This function can then be called whenever there is a need to add two numbers in the program.

 What are functions:

Functions are subprograms in a program that consists of blocks of code used to perform certain tasks. Generally, functions take a value as a parameter, process it, and then return an output. Functions help us reuse blocks of code and avoid repetitiveness. They can be used for dividing complex problems into smaller chunks. They increase code readability and reduce its size as duplicate statements are replaced by a single line of code, i.e., call to the function.

 Types of functions:

There are two different types of functions: Built-in functions/Standard Library Functions Custom/User defined Functions

 Built-in functions

Most programming languages have built-in functions which help us perform certain actions using a single line of code. These actions would otherwise require complex coding. The most common built-in functions are: sort() toString() parseInt() isNaN() encodeURI()

 User defined function:

As the name suggests, these are custom functions created by the user. The users/programmers can create custom functions for a specific task that they need to perform. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to declare a function:

First of all, we need to declare the function before we can start using it., the function keyword is used to declare a function. It is followed by the name of the function along with parameters in parentheses. The parameters are optional and are separated by commas. We then need to define the body of the function. We can put any code in a function; a function can have a single or multiple lines of code depending upon the purpose of that particular function. functionfunction_name(parameter1, parameter2, ........, parametern){ Statements;} In this example, we will declare and define a function that squares the value of the given number: functionsquare(number) { let sq = number * number;return sq;} In the example given above, the function square takes a number as a parameter. Then it multiplies the number with itself and stores it in a variable named sq. The function then returns the value that is present inside the variable sq. The sq variable is a local variable of function square and will not work outside of this function. The variables that are declared and defined in a function are that function’s local variables. On the other hand, the variables declared in the main program are global variables and can be accessed from anywhere in the program. Now we will use another example which will take two different parameters and multiply them: functionmultiply(number1, number2) { letans = number1 * number2; returnans;} The function given above is taking two different numbers as parameters. It then multiplies them with each other and stores the value in the variable ans. Then it returns the value of the variable ans to where it was called.

 How to call a function:

Declaring and defining a function specifies what the function will do when it is called. Functions can be called by their names along with parameters (separated by commas) in parenthesis. Following is the example of the syntax which can be used to call a function. function_name(parameter); In the example given below, we will call the above-mentioned function square, and we will pass number 5 as a parameter to it: square(5); The function will square the number 5 and return 25. We can verify this by calling the function inside the console.log() method: console.log(square(5)); If a function is returning a value, it returns that value to where it was called. As seen in the above example, when we called the function inside the console.log() method, the output was 25, which is the returning value of the function. We can use any variable or number in place of the parameter. A Function can be called from inside of any other function as well. We can use functions as conditions for if and loop statements as well.

 Conclusion

Functions are individual blocks of code that are written in order to perform specific actions. They are the most fundamental building blocks of almost all major programming languages. As mentioned above, all major programming languages have built-in functions. These functions help developers perform complex tasks using a single line of code. Developers also have the option to write their own functions according to the requirements of their code. In this post, we have discussed what functions are and how to declare them. Moreover, we also learned to call the declared functions.

JavaScript If else and else if statements – Explained

JavaScript is a text-based scripting/programming language used in front and back-end development. It is most commonly used on the client-side to add interactivity to a static webpage.

 What is an if statement?

The if statements are conditional statements that make decisions based on the defined criteria. These statements perform different actions under different conditions; if the defined/specified criteria are met, the block of code in the body of the if statement will be executed. Syntax of if statement: if (condition) { Statements} Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 Example

var number = 2;if (number <10) { console.log('The number is less than ten.')} In the example above, we first declared a variable named number and then assigned it a value of 2. Then we used a conditional statement to verify whether the number is less than 10. As 2 < 10, the condition of the if statement was true, and the body was executed. The if statement has the console.log() function inside it used to write a message on the console. If we change the value of the number variable from 2 to 11, then the condition will become false, and the body of the if statement will not be executed. var number = 11;if (number <10) { console.log('The number is less than ten.')} As you can see in the screenshot below, the console is completely empty.

 The If-else statements:

We can combine the if statement with an else statements as well. The else statement only runs in case the original condition is false. We will take the above-mentioned program as an example once again: var number = 11;if (number <10) { console.log('The number is less than ten.')}else{ console.log('The number is greater than ten.')} In the above-given example, we added another statement, i.e., else. As 11 is greater than 10, the original condition of the if statement was false, and the body of the else statement was executed.

 The else-if statements:

The else-if statement is used to specify a new condition that runs if the original statement is false. In this way, we can have multiple conditions that will only run if the original condition is false. Once a condition is matched/true, the other else-if statements are not checked by the editor/compiler. var number = 10;if (number <10) { console.log('The number is less than ten.')} elseif (number == 10) { console.log('The number is equal to ten.')}else{ console.log('The number is greater than ten.')} In the example given above, the number is equal to 10. So the original condition is false. So the editor moves on to the else-if condition. As the number is equal to 10, this statement is true, and the body of the else-if statement is executed. The editor does not check the else statement as one of the conditions is already true. Switch statements can be used as an alternative to if-else statements, but they can only check for equality, while the if-else statements can have a range of values as a condition.

 Conclusion

In computing, if a decision-making/conditional statement is used to run a block of code if a particular condition is satisfied. The if statements can be used in different forms depending upon the complexity of the condition. In this write-up, we discussed what is an if statement. Moreover, we also learned to use it and combine it with else and else if to check for more complex conditions.

JavaScript Interview Questions

JavaScript (originally called Mocha) was developed at Netscape Communications Corporation by Brendan Eich in 1995. It is an object-based scripting language used to develop and manage visually appealing, dynamic, and interactive content such as a carousel (slide show) on web applications. It is used on both the front end/client side and back end/server side. Most of you probably already know all this as you have come to the JavaScript interview questions article. So let’s move on. Every big company uses JavaScript to build its web applications, so JavaScript developers are in high demand all around the globe. To get a job and build a career as a JavaScript developer, you need to ace the interview. You might be asked different questions in your interview depending upon the job you’re applying for and your experience level. This article contains questions for every experience level, from fresh graduates to more seasoned developers.

 JavaScript interview questions

Here’s a list of the most common JavaScript interview questions and their answers:

 Question 1: What is the difference between declaring variables using let, var, and const?

The var, let, and const all are used to declare variables; but the scope of the variables declared with let and const is restricted to the block (A set of curly braces defines a block of code), whereas the variables declared with var are scoped globally. Here’s an example that shows the scope of the variables: if (true) { var a = 1; let b = 2; console.log(a); console.log(b);} console.log(a);// b is undefined outside of the block as it was declared using let console.log(b); if (true) { var a = 1;const c = 3; console.log(a); console.log(c);} console.log(a);// Similarly, c is also undefined outside of the block console.log(c); Another difference between var and let is that the variables created with var can be redeclared and redefined, whereas the variables created with the let keyword can only be redefined. Variables declared with the let keyword can also be redeclared in different blocks. The variables declared with the const are block-scoped, and their values cannot be changed. They cannot be redefined or redeclared and have to be initialized during declaration.

 Question 2: Differentiate between “=”, “==” and “===” operators?

The = is an assignment operator and is used to set the value of a variable. The == operator is used to compare the value of two variables, whereas the === operator compares the values and the types of two variables. The == operator will return true if we compare ‘1’(string) with 1(integer), whereas the === operator will return it as false: '1' == 1'1' === 1if ('1' == 1) { console.log(true);}else { console.log(false);}if ('1' === 1) { console.log(true);}else { console.log(false);}

 Question 3: Difference between “undefined” and “null”?

In JavaScript, a variable is assigned the undefined value by default if it has not been initialized, whereas the null value has to be manually assigned to a variable.

 Question 4: How to assign properties to an object?

Two different methods are used to assign properties to objects: By using the dot “.” operator By using the square brackets syntax var user = {firstName:"Mary", lastName:"Jane"}; user.age = 33; user['id'] = 05;

 Question 5: What is the difference between a statically and dynamically typed language?

Statically typed languages require you to define the variable’s data type while declaring it, whereas there is no such restriction in dynamically typed language. The dynamically typed languages perform type checks at runtime, whereas the statically typed programming languages perform tasks simultaneously. A variable can be used to store any data type in a dynamically typed language, while in a static language, a variable can only store one data type. JavaScript, Python, and Ruby are examples of dynamically typed languages, while C, C++, and Java are examples of statically typed languages.

 Question 6: What is JavaScript hoisting?

JavaScript has a default behavior called hosting, which moves all the variable and function declarations to the top of the scope. A variable can be used before it is even declared.

 Question 7: Difference between pop(), push() and shift(), unshift() methods

The pop() and push() methods are used to remove and add an element/item at the ending point of an array respectively. Whereas the shift() and unshift() methods are used to remove and add elements/elements from the start point of an array: var intArr = [23, 45, 67]; intArr.pop(); // returns the removed item console.log(intArr); var intArr = [23, 45]; intArr.push(67); // returns the new array length console.log(intArr); var intArr = [23, 45, 67]; intArr.shift(); // returns the removed item console.log(intArr); var intArr = [45, 67]; intArr.unshift(23); // returns the new array length console.log(intArr);

 Question 8: What is the “this” keyword

In JavaScript, this keyword has a different meaning depending upon where it is being used. The this keyword used alone code refers to the global object, whereas when used with a method, it refers to the object which owns that particular method. It also refers to the global object when used in a function, but it is undefined in a function in strict mode. The this keyword used in an event points to the element that is receiving the event.

 Question 9: What are classes?

Classes are not native and were only (relatively) recently added to JavaScript. They are just syntactic sugar built on top of prototypes. They are used as blueprints/templates for creating objects.

 Question 10: What will the following code return:

typeof typeof 10; The code is given above returns “string.” It can be divided into two different pieces: typeof 10 The type of the returned value of typeof 10 console.log(typeof 10); console.log(typeof 'number');

 Question 11: What does adding ‘use strict’ at the top of the JavaScript source file do?

The ‘use strict’ is added at the top of the JavaScript source file to run the code in strict mode. It converts JavaScript from a dynamically typed language to a lot more strict. It prevents you from using undeclared variables. The ‘use strict’ makes the JavaScript code secure and encourages the developer not to use the bad syntax previously accepted.

 Question 12: What are cookies?

Cookies are text files that store the information of the user at the time of browsing. They preserve the state of the user. Cookies are used to remember the user’s information each time the user sends a new request to the server. JavaScript has a built-in property, “document.cookie,” which can be used to read, write and modify the cookie file.

 Question 13: What is setTimeout?

setTimeout() is a native method of JavaScript that is used to call a function after a defined amount of time.

 Question 14: How are javascript and node.js different?

JavaScript is a scripting language, whereas node.js is an environment and interpreter running JavaScript outside a browser.

 Question 15: What is closure?

In JavaScript, closure is a function that is declared and defined inside another function. The function that is nested inside another function can access its own variables and the variables of its parent function, and the global variables. Example: var one = 1; functionparent(){ var two = 2; functionchild() { var three = 3; console.log(one + two + three); } child();} parent();

 Question 16. Can we store objects in an array of javaScript?

Yes, we can store anything in the array of JavaScript. Not even objects but arrays of objects within an array or functions.

 Question 17. What is the datatype of an array?

The data type of an array is an object because it stores data and behaves totally like an object. Using the typeof() operator over an array element will show the variable as an object. var arr = [1,3,6,54] console.log(typeof(arr)); Output However, if you really want to know whether a variable is an array or object, you can use Array.isArray() method:

 Question 18. Is there any associative array?

No, javascript does not support arrays with the named indices. For that purpose, objects are available.

 Question 19: What does a map() function do?

The map() function is used when we need to iterate through the whole array and change the values of each element of an array. For example, if we have a list of numbers and we want to add 5 to each number: var arr = [20, 30, 40, 50]; arr.map((n)=>{return n+5;});

 Question 20: What will be the output of 30+50+“20”?

The output of the given expression will be 8020. Since 30 and 50 are integers, they will be added as integers, and the answer will be 80. Later, “20” is a string, so 80 will be concatenated with “20,” and the final result will be “8020”.

 Conclusion

Applying for a new job and going through an interview can feel like an overwhelming task and can cause great anxiety, but you need to trust yourself. This article contains some of the most common interview questions asked by interviewers when applying for a “JavaScript developer” position.

JavaScript Objects/Dictionary – Explained

Objects are data types used to store related data; They are a collection of named values or variables used to store multiple values; these values are stored in the form of name:value pairs. Objects have properties and methods. Methods are basically functions written as properties of an object. The best way one can learn about JavaScript objects is by comparing them with real life objects. Objects in real life have different properties and can do different tasks, e.g., a Bicycle is an object; it has properties like colour, model, name, and methods like start, break, stop. Now all the Bicycles have these properties; every Bicycle has a colour, model, and name but the value of each of these properties may differ for every Bicycle. Similarly, all the Bicycles perform these methods but at different times.

 Difference between objects and dictionaries:

The data stored in the form of key-value pairs is called an Object or a Dictionary. Objects and dictionaries are similar; the difference lies in semantics., dictionaries are called objects, whereas, in languages like Python or C#, they are called dictionaries.

 How to use Objects?

Now we will create an object named user with different properties using JavaScript as an example: const user = {fName:"Mary", lName:"Jane", age:23, id:01}; The user object given above has four different properties, i.e., fName, lName, age, and id. These properties have Marry, Jane, 23, and 01 as values, respectively. JavaScript is syntactically a dynamic language, so we can also declare the object in the following way for better readability: const user = { fName: "Mary" , lName: "Jane" , age: 23 , id: 01}; Generally, objects are declared using the const keyword, and their definitions can consist of multiple lines.

 How to access a property present inside an object?

Two different methods can be used to access and assign properties to an object: By using the dot “.” operator By using the square brackets syntax Following is the syntax used in the dot operator method: Object_name.property_name The syntax for square bracket method is given below: Object_name['property_name'] For example, if we want to access the property age in our object user, we can do it in two different ways: const user = { fName: "Mary" , lName: "Jane" , age: 23 , id: 01}; console.log(user.age); console.log(user['age']); We can also modify the value of the property by using the object_name.property_name and the object_name[‘property_name’] syntax: var user = { fName: "Mary" , lName: "Jane" , age: 23 , id: 01}; user.age = 24; console.log(user.age); user['age'] = 25; console.log(user['age']); Similarly, methods can also be accessed in the same way by using the dot operator. Now we are going to add a method to our user object. const user = { fName: "Mary" , lName: "Jane" , age: 23 , id: 01 , birthYear() {const date = newDate(); Year = date.getFullYear() - this.age;return Year; }}; console.log(user.birthYear()); In the example given above, we have declared a method inside of the object user. This method subtracts the user’s age from the current year to return the user’s birth year. The ‘this’ keyword in the example refers to the object that owns the age property. This keyword is used to access the value of a property within an object. Objects can also be declared using the Object constructor along with the new keyword: const user = newObject();// Assigning Properties and Property Values user.fName = "Marry"; user.lName = "Jane"; user.age = 23; user.id = 01;

 Conclusion

Apart from the primitive data types, almost everything else is an object. The new keyword can convert primitive data types such as Booleans, numbers, and strings into objects (not recommended). JavaScript has some built-in objects such as Date and Math. We also have the option to create our own custom objects. This guide taught us to create an object and assign it to different properties, property values, and methods. We also learned to access and manipulate/modify the properties and methods present in an object.

How to use JavaScript Array Reduce Function

Javascript provides many built-in array functions for getting tasks done quickly and in an efficient way. Javascript reduce() function is one of those popular functions used to iterate over an array’s elements and get the desired result. In this post, we will grasp the concept of the javascript reduce() function. What is a reduce() function, and how can we use it to help in simplifying the Javascript code and complete the tasks efficiently and most quickly.

 What is the reduce() function?

Javascript’s reduce() function for the array is used to reduce the array into a single output value. The reduce() function takes the element of an array one-by-one, performs an operation, and returns a single output value. Let’s explore and dig more into it to understand the syntax and its functionality, along with a couple of examples.

 Syntax:

array.reduce(function_name, initialValue); The interesting part of the array’s reduce() function is that it can take a callback function with four arguments. The syntax of the callback function and the sequence of arguments will go like this: function function_name(accumulator, value, index, array) { ...} In the call back function of reducing () method: The first parameter is an accumulator that stores the result after each iteration. The second parameter/argument contains the value of the current array element during the iteration. The third parameter is the optional parameter which is the current index of the array element during the iteration. Lastly, we can also pass the array itself to the callback function for having some custom functionalities inside the callback function. We can also pass the initial value to the function. The initial value will be the starting value of the accumulator. Let’s try a couple of examples to see its implementations Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use reduce() function

The best example to understand the reduce() function is the addition of numbers stored in the array elements.

 Example 1:

Suppose we have an array of numbers and we want to add all of these numbers: var numbers = [23,76,38,55,10] The first way to add these numbers is to use a for loop: var sum = 0;for (leti = 0; i<numbers.length; i++) { sum = sum + numbers[i];} console.log(sum); Although we have got the Sum as output, why not use a smart and easy way to perform the same calculation using the reduce() method of the array, where we do not have to mutate the variables like “sum.”

 Using of reduce() function:

The reduce() function to calculate the sum will go like this: var sum = numbers.reduce(addNumbers, 0); function addNumbers(total, num) {return total + num} console.log(sum); In the above code, you can see that we have first passed the addNumbers function to the reduce() function, and in the addNumbers function definition, we just added each number to the accumulator variable total and returned its value. Once the reduce() function adds all the numbers in the numbers array, it will store the final result in the sum variable. Lastly, we have just consoled the sum variable to verify whether our reduce() function worked fine or not. By looking in the screenshot provided above, you can verify that the reduce() function has added all the numbers and shown the result in the console, which is 202 and perfectly calculated. Another shorter and easier way to write reduce() function is to make the callback function an arrow function: The syntax of writing the callback function within the reduce() function’s parentheses will be like this: var sum = numbers.reduce((total, num) => {return total + num}, 0); console.log(sum); Alright, this was the simple example in which we have an array of numbers only; what about the array of objects. Let’s try that one as well.

 Example 2:

Suppose we have a list of students in an array, and we want to calculate the total fees of all the students: var students = [ { id: 1, name: "John," age: 12, fee: 8500 }, { id: 2, name: "Bob", age: 14, fee: 9000 }, { id: 3, name: "Steve", age: 10, fee: 8000 },] The reduce() function to calculate the total fees will go like this: var totalFees = students.reduce((total, student) => {return total + student.fee}, 0); console.log(totalFees); Now, the only difference in this code is that a single object is passed as a value to the callback function, and inside the definition of the callback function, we have accessed the fee and added it into the accumulator variable. By looking at the screenshot attached above, you can see that students’ fees are added and displayed as an output. So this is how we can access the objects of an array in the reduce() function.

 Conclusion:

In this post, we have learned what a reduce() function is and how we can use it to help in simplifying the Javascript code and completing the tasks efficiently and quickly. We have learned that the reduce() function reduces the array into a single output value. The reduce() function takes a callback function applied to every element of the array and returns a single output value. This post is all about JavaScript’s reduce() function and its usage. It contains some basic examples that help in understanding the reduce() function.

JavaScript String includes/contains

The includes() method is a searching algorithm used to find a substring within a string or to find elements within an array. includes() method returns boolean values (It returns either true or false). So it can be used as the condition for an if statement or a loop. In this how-to guide, we will learn how to use the includes() method to find a substring in a string; but first, let’s discuss the syntax of includes() in JavaScript.

 Syntax:

string_name.includes(substring, starting_point) array_name.includes(element, starting_point) The include() method takes two parameters:
    substring/element: The first parameter is required. It is the substring/element which needs to be found within the string/array. starting_point: This parameter is optional. It gives the position at which to start the search. It is 0 by default.

 Difference between includes() and contains()

The includes and contains both are searching algorithms used to find a substring within a string or find elements within an array. The includes() is a method native to JavaScript, whereas contains() is used in other languages such as Java. So from here on forward, we will only use includes() in our article. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing + , and in the Advanced tab, check “Show Develop menu in menu bar”).

 How to find a substring in a String (JavaScript)

Now we will use the includes() method to find a substring within a string: var str = 'Welcome to Linux Hint!';if(str.includes('to Linux')){ console.log('Success');} In the example above, we first declared a string; and then we assigned it a value. On the next line, we used the includes() method as a condition for an if statement and passed it a string as an argument. As that string is present in the original string named str, the includes() method will return true, and the body of the if statement will be executed. If the includes method does not find the substring in the original string, then the condition would turn false, and the body of the if statement would not be executed. We can also pass variables as an argument to the includes() method. var str = 'Welcome to Linux Hint!'; let find = 'Linux';if(str.includes(find)){ console.log(`The string does contain "${find}"`);} The includes() method is case sensitive. var str = 'THIS STRING IS WRITTEN IN UPPER CASE';if(str.includes('this string is written')){ console.log('The required string found');}else{ console.log('Could not find the required string');} We can also pass another parameter to the includes() method, which specifies where it will start the search. var str = 'THIS STRING IS WRITTEN IN UPPER CASE';if(str.includes('STRING', 5)){ console.log('The required string found');}else{ console.log('Could not find the required string');} var str = 'THIS STRING IS WRITTEN IN UPPER CASE';if(str.includes('STRING', 6)){ console.log('The required string found');}else{ console.log('Could not find the required string');} Similarly, this method can also be used to find an element within an array. vararr = ['Lion', 'Monkey', 'Rhino', 'Dog', 'Cat'];if(arr.includes('Monkey')){ console.log('The required element found');}else{ console.log('Could not find the required element');}

 Conclusion

When working with arrays or strings in a programming language, you will often need to find whether they contain a specific element or a substring. The includes() method helps us figure that out. In this how-to guide, we have learned how to use the includes() method to find a substring/element in a string/array. Moreover, we also discussed the type and parameters we can pass to the includes() method.

JavaScript Switch Statement – Explained

A switch statement evaluates the value of a variable or an expression against a set of values. Each value in a switch statement is called a case. When a case is matched with the variable’s value, the code present in the body of that case statement is executed.

 When to use a Switch Statement?

Switch statements are an alternative to if-else statements. Following is the list of differences and similarities between the switch and if-else statements: For an, if statement, the condition can be a range value, whereas a switch statement can only take a single integer, string object, or enumerated value as its condition. If-else statements are great for boolean conditions, whereas a switch statement works with fixed data values. The condition in an if-else statement can be an equality or any other logical expression, whereas a switch statement can only work with equalities. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing +, and in Advanced tab check “Show Develop menu in menu bar”).

 How to use a switch statement?

In this example, we will make a simple program using a switch statement. But first, let’s discuss the syntax of switch statements.

 Syntax

switch(expression) {case a: Statementsbreak;case b: Statementsbreak;default: Statements} The switch statement evaluates the variable or the expression present between the parentheses (). It compares it with each case present in the switch statements body. If the first case is true, then the statements present in its body are executed. If the second case is true, then the statements present in the second case’s body are executed. The break and default statements are optional. The statements present under default are only executed in case all the case statements are false. The break statement is used to exit the body of the switch statement once a case is matched with the expression. If we do not use a break statement, then the switch statement will evaluate the expression against every case even if one of the cases is true. var car = "Toyota Prius";switch(car) { case"Toyota Prius": console.log("Car Name: Toyota Prius\nFuel Economy: 18/21 KM/L");break;case"Toyota Vitz": console.log("Car Name: Toyota Vitz\nFuel Economy: 20/22 KM/L");break; case"Toyota Corolla": console.log("Car Name: Toyota Corolla(Axio)\nFuel Economy: 19/22 KM/L");break; default: console.log("This car is not present in our Database.")} Output: In the example given above, first, we declared a variable named car and assigned it a value. Next, we passed the variable car as an argument to the switch statement and gave it three cases. The switch statement will check the value of the variable car against each case until a match is found. Then it will execute the body of that particular case and then terminate the switch statement using the break statement. In the example above, as the value of the variable car is ‘Toyota Prius,’ the switch statement only checks against the first case, and the switch statement is terminated. But if we modify the value of the variable car in the following way: var car = "Toyota Corolla"; Then the switch statement will check against every case, and the output will be: If we put the name of any other car which is not present as a case in our switch statement, then the body of the default statement will execute, and the output will change to: var car = "Toyota Aqua";

 Conclusion

Switch statements are used to check multiple conditions on a single variable. Switch statements are an efficient alternative to if-else statements. If statements can evaluate almost all types of data while switch statements can only evaluate integers or characters. You can use them in your code, depending on your style. In this post, we have learned what switch statements are. Moreover, we also learned about when we should prefer them over other conditional statements.

JavaScript vs. Java

Many novice developers have a misconception that Java and JavaScript are similar. These two languages are nothing alike except their names. In this write up we will discuss the differences and pros and cons of using Java and JavaScript.

 What is JavaScript?

JavaScript is an object-based scripting language created at Netscape Communications Corporation by Brendan Eich in 1995. It is used to add interactive and dynamic designs to static HTML-based web applications. It was originally designed to only work in browsers, but with node.js, it can even be used for server-side development.

 What is Java?

Java is a class-based, object-oriented programming language. James Gosling created it at Sun Microsystems. It was created with the motto write once, run anywhere. It can run on almost all platforms as it uses a virtual machine platform to run its compiled code.

 Similarities between JavaScript and Java:

Both Java and JavaScript inherit their syntax from C and are used in web development. These are only a few similarities these languages have.

 Differences between JavaScript and Java:

JavaScriptJava
It is an object-based scripting/programming language that can run in any browser.It is an object-oriented programming language.
It needs environments like node.js to run outside of a browser.It uses its own virtual machine to run its code.
It is a dynamically typed language.It is a statically typed language.
It is more relaxed towards the syntax.Variables in Java must be declared and
Variables can be used without defining their types.The data types of variables must be defined before using them.
It checks data types at run time.It performs data type checks at compilation time.
It is an object-based scripting language where.It is a class-based programming language.
In Javascript, objects are based on prototypes.In Java, no program can be created without classes.
JavaScript is mostly combined with HTML and CSS to make a complete web application.Java can work as a stand-alone language. It doesn’t need to be integrated with other languages.
JavaScript files have .js extensions.Java files have .java extensions.
JavaScript is ideal for beginners and is very easy to learn.Java is complex and hard to learn.
JavaScript source code can run directly on a browser and does not need compiling as it is a scripting language.Java code needs to be compiled before it can run on a JVM (Java Virtual Machine).
It consumes less memory than Java.Java source code needs a lot more memory than JavaScript source code.

 Conclusion

As you can see from the article, you can’t find many similarities between Java and JavaScript apart from their names. JavaScript is a scripting language for adding interactive elements to a web page, whereas Java is a high-level object-oriented programming language used for computer software development.

TypeScript vs JavaScript

JavaScript is a dynamically typed scripting language commonly used to add interactive and visually appealing elements to a static webpage. JavaScript source code can be executed without any communication with the server. Not long ago, JavaScript was only known as a client-side programming language, but now it can even run on the server-side by using environments such as Node.js. JavaScript has come a long way since it first came onto the scene. Now it is even used in Game and Mobile app development. On the other hand, TypeScript is an object-oriented programming language that is a syntactical superset of JavaScript and is used for developing large-scale applications. Any code written can be converted into TypeScript by changing the file extension from .js to .ts. Unlike JavaScript, the TypeScript code cannot run directly in a browser; It is first compiled and converted into a JavaScript file.

 Why TypeScript?

JavaScript was originally introduced as a client-side programming language in 1995 and was called Mocha. Later on, developers also started using it as a server-side programming language, but its code became more complex and dense as JavaScript grew. JavaScript was also unable to fulfill the role of an object-oriented programming language because of its complex code. These drawbacks prevented JavaScript from succeeding at the enterprise level. So TypeScript (a superset of JavaScript) was developed to cover these drawbacks.

 Differences between JavaScript and TypeScript:

TypeScriptJavaScript
A typeScript is an object-oriented programming language.JavaScript is a text-based scripting language.
It has Static typing.It has Dynamic typing.
It supports modules and has an interface.It does not support modules and does not have an interface.
TypeScript source code needs to be compiled.There is no need to compile JavaScript code.
It was Developed at Microsoft by Andres Hejlsberg.It was developed at Netscape Corp. by Brenden Eich.
TypeScript files have .ts or .tsx file extensions.JavaScript files have .js file extensions.
It is mostly used on the client-side.It can be used on both server/back-end and client-side/front-end.

 Pros and Cons of TypeScript:

Some well-Known advantages and disadvantages of Typescript are given below: Pros TypeScript catches and displays errors at compilation time, whereas, errors are highlighted at run time. Typescript supports static typing, which makes it easier to catch errors in the code. TypeScript can run in any environment/browser, device, or operating system. TypeScript is compatible with JavaScript libraries. Cons TypeScript is harder to learn and requires previous scripting experience. TypeScript code needs to be converted into JavaScript before running in a browser; thus, it takes more time to run. TypeScript is relatively new thus has a smaller community.

 Pros and Cons of JavaScript:

Some well-Known advantages and disadvantages of JavaScript are given below: Pros: JavaScript code can run directly on a browser. JavaScript can be used for both the front-end/client and back-end/server-side. JavaScript is easier to learn than Typescript. JavaScript developers have more freedom as its code offers great flexibility. JavaScript has a large community of developers. Cons: Errors are highlighted at run time. JavaScript supports dynamic typing, which can cause a lot of runtime errors.

 Conclusion

Both TypeScript and JavaScript have their advantages and disadvantages. TypeScript code needs to be transpiled and translated into JavaScript before running on a browser, whereas JavaScript can directly run on a browser. TypeScript really shines at enterprise and large-scale projects, whereas JavaScript is more suitable for small-scale projects. Large enterprises cannot afford to have run-time errors. As mentioned previously, TypeScript is a superset of JavaScript and is harder to learn, so one should only learn TypeScript once they have a complete grasp over JavaScript.

What is the Slice() method

JavaScript is the language that is used to make the website dynamic and more interactive. In any programming language, arrays play an important role in storing data and managing different types of data. Developers often need to filter out the array, merge multiple arrays, and push or pop elements from an array to fulfill the required tasks. In this post, we learn about a well-known array’s function, “slice().”

 What is the slice() method

The slice() method is used to get some specific elements of an array from a given starting index to the given ending index.

 Syntax of slice() method

The slice method takes two arguments as a parameter and provides the sliced array. The syntax of writing a slice() function is given below: arrayName.slice(startingIndex, endingIndex); The slice() method does not affect the original array and returns a new sliced array. The last element of the given range of the indices is not included in the resulting array. Let’s try to slice a couple of arrays to understand the slice() function better. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing + , and in the Advanced tab, check “Show Develop menu in menu bar”).

 How to use slice() method

Suppose we have an array of different programming languages: var arr = ["Java", "Python", "C", "C++", "C#", "JavaScript", "Perl", "Swift"]; We want to get the name of the languages from the second index to the fifth index. The syntax for getting such a result would go like this: var slicedArr = arr.slice(2,5); Now, if we console the slicedArr: console.log(slicedArr); You can see that we have got three elements from the second index to the fifth index. Note: The array index starts from zero The fifth element, the last element in the range of indices, is not included in the resulting array, as mentioned earlier.

 How to slice from the end of the array

We can also extract elements from the end of the array by providing the negative values to the slice function. Negative zero(-0) will be considered the last element of the array, negative one(-1) will be considered the second last element of the array, and so on. For example, we have an array of programming languages: var arr = ["Java", "Python", "C", "C++", "C#", "JavaScript", "Perl", "Swift"]; We want to get the elements from the fourth last index to the second last index. The slice() function for getting such a result will go like this: var slicedArr = arr.slice(-4,-1); To verify, console the slicedArr: console.log(slicedArr); We have got the exact result as we expected. So this is how we can use negative values to extract elements from the end of the array.

 Conclusion

The slice() is a built-in array method used to find and separate a subset of elements from an array. It takes two parameters: the index of the starting element of the new sliced array and the index of the element next to the last element of the new array. This method is extremely useful when we need specific elements from the array in our code. We learned how to use the slice() method to get a subset of elements from an array in this how-to guide.

JavaScript Merging and Concatenating Arrays

JavaScript is an object-based scripting/programming language that is used as a front-end web language. When the developers have to make some animation or make the website more interactive, JavaScript is the language behind all the interactivity. As we all know that arrays are usually used to store the same type of data or information. When it comes to performing some dynamic changes like showing the data of two tables at one place on the front-end, instead of querying back from the back-end, we can perform some basic functionalities on the front-end. In this post, we will have a detailed guide on how to merge or concat multiple arrays.

 What is the concat() method

To merge two or more arrays, the concat() function is used. The syntax for concatenating multiple arrays using the concat method is: array_name.concat(first_array, second_array, ..., N_array) The concat() function takes multiple arrays as a parameter and joins them together as one array. The concat() function returns a new array and does not affect the original array. Let’s try to join two arrays and have a better understanding of the concat() function. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing +, and in the Advanced tab, check “Show Develop menu in menu bar”).

 How to use concat() function

Suppose we have two arrays and we want to make them a single array: var arr1 = [10,20,30,40];var arr2 = [50,60,70,80]; To concat them into an array, the following statement will be used: var arr3 = arr1.concat(arr2); Now, if we console the arr3: console.log(arr3); You can see that two arrays arr1 and arr2, are concatenated in arr3. Now, let’s say we want to concatenate these three arrays. To join multiple arrays following code snippet will be used: var arr4 = arr1.concat(arr2, arr3); Another way for doing the same task would go like this: var arr4 = [].concat(arr1, arr2, arr3); Now, if we take a look at the arr4: console.log(arr4); You can see that all three arrays are merged into the arr4 as we expect it to do. This is how we can merge two arrays using the concat method.

 Concatenate arrays using spread operator

Another way to merge multiple arrays is to use the spread operator. Merging two arrays using a spread operator is really simple. Just prepend three dots to the array name and provide them as an array element to a new array. For example, we have two arrays: var arr1 = [10,20,30,40];var arr2 = [50,60,70,80]; Now to join them using the spread operator, simply use the following statement: var arr3 = [...arr1, ...arr2] Now, console the arr3 to verify: console.log(arr3); You can see that arr1 and arr2 are joined perfectly using the spread operator.

 Conclusion

The concat() method is useful when manipulating the data present in arrays without modifying the original arrays. When working on web applications, we might need to show the data of different arrays combined. We can do this by using the contact() method. This method will help us perform our task without changing the actual arrays that might be needed later in their original state. In this how-to guide, we learned to use the concat() function. Moreover, we also learned to use the spread operator, which is also used to merge arrays. The spread operator has become a more popular way of merging arrays in recent times.

JavaScript Array Contains/Includes

The includes() is a built-in method of JavaScript that is used to discover whether an element is present in an array or not. It can also be used to find substrings in a string. The returning value of the includes() method is a boolean, which means it either returns true or false. This method can be used as a condition for loops and decision-making statements. In this how-to guide, we will learn how to use the includes() method to find an element within an array; but first, let’s discuss the syntax of includes() in JavaScript. The syntax of the “Includes” method is mentioned below. array_name.includes(element, starting_point) The include() method takes two parameters:
    element: The first parameter is required. It is the element that needs to be searched within the array. starting_point: This parameter is optional. It gives the index at which to start the search. It is 0 by default.

 Difference between includes() and contains()

The includes and contains both methods search for a substring within a string or find elements within an array. The includes() is a method present, whereas contains() is not present. It is used in other languages such as Java. The includes() and contains() both have the same functionality, but, this functionality is termed as includes(), while in other programming languages such as Java, it is called contains(). Since this article is about JavaScript, we will only use includes() in our article from here on. Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console: Use the F12 key in Chrome and other chromium-based browsers. Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla. Use Option + + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing +, and in the Advanced tab, check “Show Develop menu in menu bar”).

 How to search an element/item in an array using includes method (JavaScript)

Now we will use a couple of examples to show how the includes() method actually works. var arr = ['John', 'Ron', 'James', 'Jack', 'Chris'];if(arr.includes('James')){ console.log('The required element found');}else{ console.log('Could not find the required element');} In the above example, we first declared an array and assigned it a few elements. Then we used the includes() method as a condition for the decision making with the if statement. We passed one of the elements of the array as an argument to the includes() method. As that element is present in the array, the includes() method returns true, and the body of the if statement is executed. If the includes() method does not find the element in the array, then the condition would return false, and the body of the else statement would execute. Variables can also be passed as an argument to the includes() method. var arr = ['John', 'Ron', 'James', 'Jack', 'Chris']; let find = 'James';if(arr.includes(find)){ console.log(find);}else{ console.log('Not Found');} The includes() is a case sensitive method: var arr = ['John', 'Ron', 'James', 'Jack', 'Chris'];if(arr.includes('james')){ console.log('The required element found');}else{ console.log('Could not find the required element');} Now we will also pass the second parameter to the includes() method, which tells the starting index of the search to the method: var arr = ['John', 'Ron', 'James', 'Jack', 'Chris'];if(arr.includes('James', 2)){ console.log('The required element found');}else{ console.log('Could not find the required element');} var arr = ['John', 'Ron', 'James', 'Jack', 'Chris'];if(arr.includes('James', 3)){ console.log('The required element found');}else{ console.log('Could not find the required element');} As the first index in an array is 0, the James element is present at the 2nd index. So if we change the starting point of the search to 3, then the includes() method will not be able to find it. As mentioned above, this method can also be used to search for a string within a string: var str = 'Hello World!';if(str.includes('Hello')){ console.log('Success');}

 Conclusion

We can use the includes () method to figure out whether a certain element is present in an array; we can use the includes() method. It is a searching algorithm present which helps when we need to find a substring within a string or an element within an array. We have learned how to use the includes() method to find an element in an array in this how-to guide. Moreover, we also discussed the type and parameters we can pass to the includes() method.

How to Install Node.js and Npm on Ubuntu 20.04

Node.js is a free and server-side platform for JavaScript runtime environment set up on Chrome (V8) JavaScript Engine. The Node.js environment is developed to build back-end solutions and be famous for networking applications, full-stack, and front-end development. The “npm (Node Package Manager)” is used to install multiple node packages and dependencies. Almost all the node packages are available on the world’s largest package manager registry. We have multiple resources to download the Node.js and npm on Ubuntu 20.04, but why not select the effortless ways. In this guide, we will see the two approaches for installation:
    Install Node.js and npm from Ubuntu Official Repository Install Node.js Using nvm
Let’s begin:

 How to Install Node.js and npm from Ubuntu Official Repository

To download Node.js and npm from Ubuntu’s repository is a pretty straightforward and simplest way. What we need to do is, open the terminal and update all the package index of the Ubuntu system: $ sudo apt update Run the following command to install the Node.js environment with all the necessary packages on Ubuntu machine: Once done, verify if the installation has accomplished by checking its version: $ node -v Through the Ubuntu official repository, the installed node.js is the latest available package. It is not compulsory to go with it; if you want to install the specific one, then move towards the 2nd approach in this guide. To install the npm library on the system is as simple as we have installed the node.js. Write the given command to initiate the installation process of the npm in the command line: $ sudo apt install npm The Node.js and the npm library have been installed on the system from the Ubuntu official repository.

 How to Install Node.js using nvm

In the above section, we have seen that through the Ubuntu repository, only the latest available package of Node.js can be installed. To get the specific version of Node.js on a system, download it through nvm that is the abbreviated form of “Node Version Manager”. As the name describes, it is the bash script consist of all node versions and allows the user to install and test any Node.js version as per requirement. To get the download link, you can visit https://github.com/nvm-sh/nvm#installing-and-updating, or you can copy the mentioned curl command in the terminal: $ curl –o- <a href="https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh">https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh</a> | bash You might face this issue, and to resolve this, install the curl command: $ sudo apt install curl Now, run the above curl command of node.js again to begin nvm installation: To source the bash file, run the given command: $ source ~/.bashrc Run the mentioned command to show the list of Node.js available versions: $ nvm list-remote Use the following syntax to install the version you want: $ nvm install [version_number] For instance, to install the node version “v10.24.1”, the command would be: $ nvm install v10.24.1 To check the list of all node versions installed on Ubuntu machine, the command is: $ nvm list

 How to Uninstall Node.js from Ubuntu 20.04

If you want to uninstall the Node.js from the system, use the mentioned command: $ sudo apt remove nodejs

 Conclusion

This write-up shows how to install Node.js and npm on Ubuntu 20.04 using Ubuntu repository and nvm methods. Node.js is an open-source networking and server-side platform used to build JavaScript runtime applications. The npm is a package manager for all the available versions of Node.js, while the nvm manager is used to download a specific version.

How Do You Use Material Designs in Vue.js?

Material design is the world’s most popular design language built by Google Inc. It provides a huge number of components or design templates to give a Material look to your application. Some material design-based front-end frameworks are created by the community and used for creating interactive and intuitive web applications. This post will learn about the installation of ‘vue-material’ and learn to use it in the Vue.js Framework. Vue Material is a Google Material Design-inspired library used for building web apps.

 Installation of Vue Material

Vue material library can be used as Vue components in a Vue project. Before getting started with the Vue material installation, it is assumed that you are familiar with HTML, CSS, and Javascript. You have set up the Vue Project, and you have a good editor installed on your system like VS code. If you have not set up the Vue project yet, you can follow the procedure given below to set up a Vue project quickly.

 Setup Vue Project

To set up the Vue project, first, check whether Vue.js is installed on your system or not by typing the command given below: $ vue --version If you have not installed it yet, type the command given below to install Vue.js globally on your Operating system: $ npm install -g @vue/cli After successfully installing Vue.js globally on your Operating system, create the Vue project by typing the “vue create” command given below, followed by the project name: $ vue create vueprojectname It will ask you to either select the preset or select your own custom preset for the Vue project. After configuring or selecting the default preset, the Vue project will be created in a while. After creating the Vue project, navigate to the newly created project’s directory using the “cd” command. $ cd vueprojectname At this stage, you have successfully set up the Vue project.

 Install Vue Material

Once your system is ready, and the Vue project is set up! You can install the “vue-material” using the Yarn or NPM. For installing ‘vue-material’ using the Yarn package manager, type the command given below: $ yarn add vue-material OR For installing ‘vue-material’ using the NPM package manager, type the command given below: $ npm install vue-material --save Alright! Once the ‘vue-material’ isinstalled, You have to enable it in the main.js file. import VueMaterial from 'vue-material'import 'vue-material/dist/theme/default.css'import 'vue-material/dist/vue-material.min.css' Vue.use(VueMaterial) After enabling the “vue-material,” you can now use it in your Vue project.

 How to Use Vue Material in Vue

To use Vue Material with Vue, ‘vue-material’ provides various components to use as a Vue component. For example, a button can be created using the ‘vue-material’ like this. <md-button class="md-raised md-primary">Primary</md-button> For knowing about further components, feel free to visit the official getting started page of Vue Material. This is how simple it is to install and start using Vue Material in a Vue project.

 Conclusion

Vue Material is a trendy material design component library used for building web apps. In this post, we walk through Vue Material’s installation in a Vue.js project and see how to enable it and use it. With the combination of such two robust libraries, we can speed up the development process and beautify our web application to the highest limits.

How to Change Port Number in Vue CLI

Vue.js is a robust and trendy front-end framework. It is recognized as the combination of two spectacular frameworks, Angular and React, using the templating syntax of Angular and props method of React. It provides the traditional HTML and CSS way to create a component, and it is known for making front-end applications really fast and in an easy way. However, we often have to face some problems and issues or just want some different configuration, so we will have a look at a scenario where we need to change the port number in the Vue CLI project. Let’s start.

 Default Port Number of Vue CLI

When you run a Vue project using the npm run serve command, the port number 8080 is automatically assigned to the Vue project, and it runs on that port number. While running a Vue.js project, the terminal shows the output something like this: $ npm run serve In the screenshot given above, the default port assigned is 8080, where the project is running. In a rare scenario, if port 8080 is busy, port 8081 is assigned to the Vue project, and this is how it continues until it finds the free port number. But, what if you want to change and assign some other port number of your own choice. Let’s see and learn how to change the default Port Number in the Vue CLI project.

 Change the Default Port Number of Vue CLI

Well, there are two ways to change the default assigned a port number to the Vue.js project. One is to change the port number temporarily, and the second one is to permanently change the port number. So, let’s begin with the first method of changing the port number of Vue CLI. Method 1: Change Port Number TemporarilyThe port number of the Vue CLI project can easily be changed while running the Vue.js project using the npm run serve; you simply have to append — –port with the port number of your desire to the npm run serve command as shown in the command given below: $ npm run serve -- --port 4000 Now, when the project is compiled successfully, you can see that the port number is changed to 4000. You can witness in the screenshot given above that the Application is running at port 4000, but this port is assigned temporarily until the app is running. Once you terminate the batch and run the project without providing the port to the npm run serve command, then the default port 8080 will be assigned again, or otherwise, you have to assign the port every time you run the application. Luckily, we have another method provided by Vue.js, using which we can permanently change the port number of our Vue project, so let’s go ahead and see how to change the port number of the Vue CLI project permanently. Method 2: Change Port Number of Vue CLI project permanentlyIf you are interested in changing the default port number of your Vue.js project permanently. Simply follow the steps given below, and you will have your own desired port number assigned to your Vue.js project. Step 1: Create a new vue.config.js file at the root directory First of all, you need to create a new file at the root directory of your project with the name vue.config.js Step 2: Add Port Number in the vue.config.js configuration file After creating the configuration file, open it up and provide your desired port number as a key-value pair inside the devServer object in the module.exports as shown in the code snippet below: module.exports = { devServer: { port: 3000 } } Once you have done that, save the application by pressing CTRL + S keyboard shortcut keys and start the application. Step3: Run the Application Now, start the application using the npm run serve command and without appending any port number. $ npm run serve You will witness that the port number 3000 is assigned successfully, and the application is running on your provided port number in the vue.config.js file. This is how you can change or set the port number of your own choice in the Vue CLI project.

 Conclusion

This post has learned two different ways to change or set the Port Number temporarily and permanently in a Vue CLI project and explained in a profound and easy-to-understand step-by-step method.

How to Create Components in Vue CLI

Vue.js provides the Vue CLI to provide the vue command inside the terminal for quickly scaffolding a new project of Vue.js and run the Vue.js project using the vue serve command. Vue.js also provides the graphical user interface for managing the projects using the vue ui command. Vue.js is recognized as combining two spectacular frameworks, Angular and React, using the templating syntax of Angular and props method of React. It provides the traditional HTML and CSS way to create a component, and in this post, we will go through the process of creating and understanding components in Vue CLI.

 Prerequisites

Before getting started with this, there are some prerequisites that you must have: Basic knowledge of HTML, CSS, and JavaScript. Node.js installed on your Operating System.

 Verify the Vue CLI installation

First of all, make sure that you have the latest Vue CLI installed on your system. You can verify either Vue CLI is installed or not on our system by typing the command given below: $ vue --version If it is installed, you will have the latest version of Vue CLI printed out in the terminal. Otherwise, if it is not installed, you can either use the NPM package manager or Yarn package manager to install the Vue CLI. In order to install it using the NPM package manager, you need to type the command given below in the terminal: $ npm install -g @vue/cli In the above command, the -g flag is used for installing Vue CLI globally on your system. Once the Vue CLI is completely installed, you can verify it by typing the command given below: $ vue --version You will have the latest version of Vue CLI in the output.

 Project Creation

Now, suppose you are going to set up the whole Vue project on your own. In that case, it is not a good choice to reinvent the wheel; the Vue project can be created using the vue command in the terminal because the Vue CLI provides the already generated templates to start with the Vue project. To create the Vue application, simply type the command given below in the terminal: $ vue create project-name Make sure to replace the project-name with your desired project name and hit Enter. After a couple of seconds, it will prompt selecting the default preset or selecting some features manually. If you want to have some custom features, select “Manually select features,” hit Enter, and you will be prompted with some options like selecting the Vue version, adding Vuex, or Router. Select your desired option and hit Enter. Answer some necessary configuration questions and save the preset for future projects. The Vue project will be created in a while using the Vue CLI, and you can start the development in Vue.js.

 Starting the Vue application

Once the Vue project is created, you can start the project by first navigating to the project’s directory using the cd command in the terminal: $ cd project-name In the project’s directory, start the Vue application by typing the command given below in the terminal: $ npm run serve After the ignition of the Vue application, visit the http://localhost:8080 in the address bar of your favorite browser: You will have the Welcome screen of the Vue.js project.

 Creation of a Component in Vue

For creating a component in the Vue project, create a .vue file in the components folder and provide it the name of your choice. Now, in this newly created .vue file, you can write HTML, Javascript, and CSS in the <template>, <script>, and <style> tags respectively. Open up the .vue file and write the code that you want to write. For example: <template> <div class="new-component"> <h1>A New Component</h1> <p>This is a text inside the NewComponent.</p> </div></template> Once you are done with the HTML part, give this component a name in the <script> tag as shown in the code snippet below: <script> export default { name: 'NewComponent',} </script> After successfully creating the component, let’s see how to import it and use it on some other page or component.

 Importing of a component in Vue

The import syntax for importing a component in any other component of Vue is pretty simple and easy; you just have to import the component inside the script tag using the ES6 syntax as shown in the code snippet below: <script> Import NewComponent from '@/components/NewComponent.vue'; export default { name: 'App',} </script> After importing the component successfully, all you need to do is to create an object with the name of components and provide the name in the components object as shown below: <script> Import NewComponent from './components/NewComponent.vue'; export default { name: 'App', components:{ NewComponent }} </script> Now, you can use it anywhere inside the <template> tag of the component. For example, if we want to import it into the App.vue, the syntax would be like this: <template> <div id="app"> <img src="./assets/logo.png"> </div> </template> After completing all this setup, save each and every file that you have changed and go back to the browser You can witness in the screenshot attached that the component is imported successfully and perfectly fine on the web page.

 Conclusion

Creating, importing, and using a component inside any other component of Vue.js is as easy as saying it. In this post, we walk through the whole process of creation, addition, and usage of a component in Vue.js.

How to Use Bootstrap with Vue.js

Bootstrap is one of the world’s most popular front-end CSS frameworks that provides many components or design templates to create quick and fast responsive web applications. It is an open-source and free-to-use framework for building modern websites enriched with HTML and CSS templates or user Interface elements like buttons, icons, and forms. In this post, we will learn first to install and then use Bootstrap with Vue.js Framework.

 Installation of Bootstrap

There is a “bootstrap-vue” library built especially for Vue.js and can be used as Vue components with the same features as Bootstrap. Before getting started with the “bootstrap” or “bootstrap-vue” installation, it is assumed that you are familiar with the HTML, CSS, and Javascript, you have set up the Vue Project, and you have a good editor installed on your system like VS code. If you have not set up the Vue project yet, you can follow the procedure given below to set up a Vue project quickly.

 Setup Vue Project

To set up the Vue project, first, check whether Vue.js is installed on your system or not by typing the command given below: $ vue --version If you have not installed it yet, type the command given below to install Vue.js globally on your Operating system: $ npm install -g @vue/cli After successfully installing Vue.js globally on your Operating system, create the Vue project by typing the “vue create” command given below, followed by the project name: $ vue create vue-project-name It will ask you to either select the preset or select your own custom preset for the Vue project. After configuring or selecting the default preset, the Vue project will be created in a while. After creating the Vue project, navigate to the newly created project’s directory using the “cd” command. $ cd vueprojectname At this stage, you have successfully set up the Vue project.

 Install Bootstrap

Once your system is ready, and the Vue project is set up! You can install the “bootstrap-vue” using the Yarn or NPM. If you want to install the simple “bootstrap” for styling purposes, you can type the command given below to install them. For installing ‘bootstrap-vue’ and ‘bootstrap’ using the Yarn package manager, type the command given below: $ yarn add bootstrap bootstrap-vue OR For installing ‘bootstrap-vue’ and ‘bootstrap’ using the NPM package manager, type the command given below: $ npm install bootstrap bootstrap-vue --save Alright! Once the ‘bootstrap’ and ‘bootstrap-vue’ are installed, You have to enable them in the main.js file. import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'bootstrap/dist/css/bootstrap.css'; Vue.use(BootstrapVue); After enabling the “bootstrap” and “bootstrap-vue”, you can now use them in your Vue project.

 How to Use Bootstrap in Vue

To use Bootstrap with Vue, ‘bootstrap-vue’ provides various components to use as a Vue component. For example, a button can be created using the ‘bootstrap-vue’ like this. <b-button variant="success">Button</b-button> For knowing about further components, feel free to visit the official documentation page of BootstrapVue. This is how simple it is to install and start using bootstrap in a Vue project.

 Conclusion

Bootstrap is a prevalent CSS front-end library used for building mobile-first and responsive web apps, and with the help of BootstrapVue, we can build such web applications using Vue. In this post, we walk through the installation of BootstrapVue in a Vue.js project and also see how to enable it and use it. With the combination of such two robust libraries, we can speed up the development process and beautify our web application to the highest limits.

Vue Watch to make Dynamic Interaction

Vue.js is a very impressive and reactive JavaScript’s front-end framework used to develop front-end websites quickly and easily. This post will learn about the watch property that is one of the most fundamental concepts. Vue.js provides a watch property to watch a variable, and on the change of that variable, it allows us to run a function so that we can make Dynamic Interaction. Let’s try an example and have some dynamic interaction using the Vue Watch property.

 Example

We will first try to change some variable at the click of a button, and then using the watch property, we will watch that variable and alter some other variable to make the dynamic changes on the web page. First, assume we have two variables.data() { return { buttonBool: true, color: "red" }} And we have bound the “buttonBool” variable with a button element in the template. <template> <div class="test"> <h1>This is a testing page</h1> <button @click="buttonBool=!buttonBool">Click me!</button> </div></template> We want to change the background color of a, let’s say, a division at the click of the button. So, first, create a div in the template. <template> <div class="test"> <h1>This is a testing page</h1> <button @click="buttonBool=!buttonBool">Click me!</button> <div></div> </div></template> Now, let’s first create a watch property and change the state of the “color” variable at the change of the “buttonBool” variable. watch:{ buttonBool(){ this.color = !this.color; }} Alright! The last step left is to change the classes of the div on the change of color variable. So, let’s do that by using the class binding feature of Vue.js. <template> <div class="test"> <h1>This is a testing page</h1> <button @click="buttonBool=!buttonBool">Click me!</button> <div :class="[color ? 'red' : 'green', 'box']"></div></div></template> Here, I have just assigned the class “red” if the state of the “color” variable is true, else “green” if the state of the color variable is “false,” and the “box” class is assigned in any case. The CSS for giving the width, height, and background color to the div is as follows. <style scoped> .box{ width: 100px; height: 100px; margin: 15px auto;} .red{ background-color: red;} .green{ background-color: green;} </style> Alright, after getting done with the coding stuff, my web page would be like this. Now, whenever I click the button, the background color of the box should get changed. And you can witness in the gif above, the color of the div is changing at the click of the button. That’s amazing, right! So, this is how we can use the Vue Watch to make dynamic interaction on the webpage.

 Conclusion

In this post, we have tried to change some variable’s state at the click or change of some other variable using the watch property of Vue.js. We have also made some dynamic changes to the web page. We have seen that at the click of the button, in the on-click attribute, we changed the variable’s state and shown that the watch property watched the variable and performed some action like changing some other variable’s state.

What is a Vue Directive, and how to use it?

A framework aims to provide such features that make the development process easier and faster for the developers. Vue.js is such a feature-enriched JavaScript framework that provides many built-in functions and directives to quickly make the development process. But, there must come some scenarios when you need some functionality that is not available by the framework, so you have to build your own. In this post, we will learn and take a look at the built-in directives provided by the Vue.js framework, and we will also learn to create and use our own custom-made Vue directive.

 Directive

Directives are attributes that you can link with the DOM elements, prefixed by the clause “v-” which helps to know the library that it is a special type of syntax used for performing some tasks. Directives are usually used for direct manipulation of DOM. Some of the most used and famous directives are “v-if”, “v-for”, and “v-show”. The directives are used to apply effects on DOM elements but reactively. Let’s understand it with an example: “v-if” Directive <p v-if= "showText"> You can view the text.</p> In the above tag, the “v-if” is a directive that will delete or add the paragraph tag “<p>”, depends on the “showText” variable’s truthiness. “v-show” Directive Similarly, we have the “v-show” directive which can perform the same functionality described above: <p v-show= "showText"> You can view the text.</p> The subtle difference between “v-if” and “v-show” is that “v-if” does not render the element while loading the page if the bound variable is not true and it loads when the variable becomes true. In contrast, “v-show” will render the element at the web page’s load time but hides it. So, “v-if” is time effective at the page’s load time and time-consuming when the variable gets true. It has to render the whole element while “v-show” is time effective upon the truthiness of the variable time-consuming at the load time of the web page. Alright! Let’s have a look at a directive that takes the argument. “v-bind” Directive Another most widely used directive is “v-bind,” which is used for interacting and updating the HTML attributes. For example, if we want to bind some variable to the “href” attribute of the <a> tag, we can bind the “href” attribute like this: <a v-bind:href="url"></a> “v-on” Directive Just like the “v-bind” directive, Vue provides a “v-on” directive for binding the variable for listening to the events fired in the DOM. For example, for listening to the Click event and binding some variable to it, the syntax would go like this: <button v-on:click="buttonBool=!buttonBool">Click me!</button> In the inverted commas, we can provide the expression as well as functions.

 Conclusion

We have learned about the directives in Vue and see how to use the directives in Vue.js. We have discussed some of the most used and basic built-in directives of Vue.js, which helps a lot and saves a huge amount of time in the development.

Vue Computed Deep Structures

When it comes to the computation of nested or deep data types like arrays or objects, Vue.js or any other programming language does not automatically detect the hierarchical change in the data. However, we all know that Vue.js provides the watch and computed properties to perform some change variables. But when it comes to nested data changes, Vue.js does not detect that. This post will learn to perform some changes by watching the nested data of arrays or objects. Before learning about watching nested data in Vue.js, let’s first understand how the watch property works?

 Watch Property

The watch property is used to watch a variable and allows the user to perform some desired tasks on the variable’s change.

 Example: Watch a Variable

For example, at the change of some variable, we want to console something. The syntax for writing such code in Vue will go like this: <template> <div class="test"> <h1>This is a testing page</h1> <button @click="boolVar=!boolVar">Click</button> </div></template><script> export default { name: "Test", data(){ return{ boolVar: true } }, watch:{ boolVar(){ console.log("Button clicked.") } }};</script> After writing the above code, the web page would be like this. If we click on the button, the state of the “boolVar” should be altered due to the button’s on-click attribute, and the watch should automatically detect the change in “boolVar” and display the message string on the console. It worked perfectly fine; the message “Button clicked” is displayed on the console. But, the watcher fails to detect the change and does not get fired when it comes to watching the arrays or objects. Let’s see a demonstration of that.

 Example: Watching an Object

Suppose we have an object in our component, and we want to display the change that happened in the object’s property. In the example given below, I have created an object with the name of “objVar,” which contains two key-value pairs, “item” and “quantity”. I have created a button where I am adding “1” to the template tag’s quantity. Lastly, I am watching the “objVar” object in the watch property and displaying a console message. <template> <div class="test"> <h1>This is a testing page</h1> <button @click="objVar.quantity=objVar.quantity+1">Click</button> </div></template><script> export default { name: "Test", data(){ return{ objVar: { item: "Item1", quantity: 1 } } }, watch:{ objVar(){ console.log("Button clicked & Quantity = " + this.objVar.quantity) } }};</script> Now, this code is supposed to display the change in the quantity of the object. But, when we execute the code and click the button on the web page: You can see in the above gif; nothing is happening in the console. The reason behind this is that the watcher does not look deep into the values of the objects, and this is the real problem to which we are going to solve now. Vue.js provides the deep property for watching deep down into the values of objects and arrays. The syntax for using the deep property and watching the nested data is as follows: <script> export default { name: "Test", data(){ return{ objVar: { item: "Item1", quantity: 1 } } }, watch:{ objVar: { deep: true, handler(){ console.log("Button clicked & Quantity = " + this.objVar.quantity) } } }};</script> In this syntax, we have set the deep property to true and rearranged the handler() function. Now, after changing the code, if we reload the web page and click on the button: Here you can see that the watcher is working and displaying the message in the console.

 Conclusion

After reading this post, watching and computing deep or nested data structures in Vue.js is not difficult anymore. We have learned how to watch the change of a value in an object or array and execute some tasks with the help of the “deep” property of Vue.js.

Vue Computed Property not updating; Troubleshooting Steps

Vue.js is a very popular JavaScript library that is known for its reactivity, flexibility, and intuitive API. However, reactivity and flexibility come with some drawbacks, leading to the developer’s performance or a headache. The computed property is a very famous and most known feature of Vue.js, which is used to update some variable or perform some calculation depending upon some other variable’s updation. This post will try to troubleshoot the problems that occurred when the computed property does not work or update what we want. Let’s have a look at the scenarios, what might go wrong, and Vue Computed Property not updating.

 Scenario # 1:

First of all, make sure you did not make any logical error like implementing the wrong logic. To avoid the possible logical errors, check the following things: Verify that variable names are correct. You are taking care of the scopes of the variable using “this”.

 Scenario # 2:

The second thing you might have mistaken in the computed property is that you are not caring about the Computed property’s side effects like editing some data inside a computed property or calling other functions. For example, reversing the array within a computed property. Suppose we have an array in our component. data(){ return{ arrVar:[1,2,3] } }, In the computed property, we are reversing the array. computed:{ arrayReverse(){ return this.arrVar.reverse(); } } But, when we run the project, it will show an error of ‘Unexpected side effect in “arrayReverse” computed property.’ because it will always do the same task again and again and reverse the original array every time. So, try to avoid data manipulation in the computed property, and it will work perfectly fine for you.

 Scenario # 3:

Another scenario could be that the computed property is stuck in an infinite loop, and it keeps on re-computing something. Since computed property watches every variable included in the computed property and reacts or gets recomputed on the change of any variable involved in this property, if you change the state of any variable inside the computed property, the computed property detects the change. It starts to re-compute itself, and it won’t be able to get out of this infinite loop. These are some of the possible ways which could lead to the computed property not updating problem.

 Conclusion

This post has gone through the most common scenarios the developers faced for Vue Computed property not updating and provided profound and to-the-point troubleshooting steps for each scenario. If you still have not found your solution yet, feel free to ask your questions on the Vue community platforms and get your questions answered within no time.

Vue Computed with Parameter

The Computed property is usually used to compute data from some other data. It is known for its reactivity because whenever a variable involved in some computed property gets changed, the whole property gets recomputed.This post will learn to pass the parameter to computed property and see how to use Vue computed with parameter. Before getting started with passing parameters to the computed property, let’s first understand the computed properties by going through the example.

 Examples

Suppose we have two variables named “firstName” and “lastName” in our Vue component: //.. data(){ return{ firstName: "", lastName: "" } },//..

 Computed Property

We want to compute a “fullName” property that will combine the “firstName” and “lastName” and recompute the fullName whenever any of the two variables “firstName” and “lastName” gets changed. So, the computed property for computing the full name would be like this: //.. computed:{ fullName(){ return this.firstName + ' ' + this.lastName; } }//.. Now let’s create some input fields and bind the “firstName” and “lastName” variables to the input fields and also bind the “fullName” property in the ‘p’ tag to view the instant change on the change of the first anime of the last name. The HTML part of this component will be like this: Alright! After having all this setup, let’s take a look at our webpage. If you have successfully written the correct code and run it, you should also have the two input fields on your web page. Let’s try to type the first name and last name and see either the “fulName” property gets computed or not. Here in the screenshot given above, you can witness the marvelous reactivity of Vue.js using the computed property. You can also witness that it is not like watching a single variable and changing some other variable’s value. Still, it is watching each variable included in the computed property and re-computing the “lastName”. Let’s see how we can pass parameters to the computed property and use it.

 Pass parameters to the Computed Property

For passing the parameters to the computed property, we just pass the parameters as we do for the function. For example, in the template, when we have bound the variable “lastName,” we want to pass some string, so the template part of our component would be like this: Now, in the computed property, the passed parameter can be utilized using the following syntax. computed:{ fullName(){ return message1 => { return `${message} ${this.firstName} ${this.lastName}` } } } This is how we can pass a parameter to the computed and get it in the property and use it. If we again look at our web page and type the First name and last name, you can have the same functionality and reactivity, but this time, the parameter passed. This is how simple and easy it is to pass a computed property parameter and use it.

 Conclusion:

The computed property is a very powerful feature of Vue.js, and we have learned that it comes in handy when we have to change them when their dependencies get changed. We have learned to pass the parameter and use it in the computed property.

How to Build A Simple Blog With Hexo Static Site Generator

In the modern age, websites are the building blocks of information. From enterprise, eCommerce, social websites to simple blogs, websites allow people to share ideas and thoughts. This tutorial will show you how you can set up a simple blog using a static site generator that is very fast and easy to use.

 What Is An SSG?

SSG, or Static Site Generator, is a web application that converts the dynamic content on a webpage into static content usually stored locally. Static site generators do not require databases and backends, thereby eliminating the need to learn how to code. It mainly focuses on writing and presenting the content.

 SSG vs. CMS

The most popular way to create websites and manage content is using CMS or Content management systems such as WordPress, Drupal, Joomla, etc. CMS systems work by creating and managing content directly using an interactive interface. Since data in a CMS is retrieved from the database, CMSs are very slow as the content is fetched and served as dynamic content. CMS systems are also prone to security vulnerabilities as they rely on external plugins written by other developers to increase functionality. On the other hand, static site generators work by creating content offline mediums such as text editors and renders the final page view upon publication. Since the content is locally-rendered, with no need for a database, the page renders faster, and load speeds are incredibly fast. Static site generators are made of pre-compiled code that acts as an engine to render the published content.

 How to Build a Static Blog With Hexo

One of the popular choices for building a static site is Hexo. Hexo is a simple, fast, and powerful SSG application written in NodeJS. Although there are other choices for building a static site, Hexo allows you to customize your site and integrate various tools. Let us look at how we can set up a simple static site with Hexo.

 Installing Hexo

Before we can build a site, we need to set up hexo requirements and install it. For this, we require NodeJS and git. Start by updating your system: sudo apt-get updatesudo apt-get upgrade Once you have your system up to date, install git sudo apt-get install git Next, install nodejs from nodesource using the command: curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -apt-get install -y nodejs Once you have Nodejs installed, we can proceed to install hexo using the command: npm install -g hexo-cli

 Working with Hexo

Once you have installed hexo, you can create a site and publish content. Let us look at how to work with Hexo. Keep in mind that this is a quick, simple guide. Refer to the documentation to learn more.

 Creating a site

To create a new hexo site, use the command below: hexo init HexoSitecd HexoSite npm install

 Understanding Hexo Directory structure

Once you initialize a new Hexo site, you will get a directory structure such as the one below: -rw-r--r-- 1 cs cs 0 Feb 8 20:51 _config.landscape.yml-rw-r--r-- 1 cs cs 2439 Feb 8 20:51 _config.yml drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 node_modules-rw-r--r-- 1 cs cs 615 Feb 8 20:51 package.json-rw-r--r-- 1 cs cs 56716 Feb 8 20:51 package-lock.json drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 scaffolds drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 source drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 themes The first file is the _config.yml contains all the settings for your site. Ensure to modify it before deploying your site because it will contain default values. The next file is the package.json file that contains the NodeJS application data and configurations. Here, you will find installed packages and their versions. You can learn more about the package.json from the resource page below: https://docs.npmjs.com/cli/v6/configuring-npm/package-json

 Creating a Blog

To create a simple blog in hexo, use the command: hexo new blog “Hello World Blog” Once created, you can file the markdown file under /source/_posts directory. You will need to use Markdown markup language to write content.

 Creating a new page

Creating a page in Hexo is simple; use the command: hexo new page “Page-2” The page source is located under /source/Page-2/index.md

 Generating and Serving content

Once you publish your content on hexo, you will need to run the application to generate the static content. Use the commands below: $ hexo generate INFO Validating config INFO Start processing INFO Files loaded in 966 ms INFO Generated: archives/index.html INFO Generated: Page-2/index.html INFO Generated: archives/2021/index.html INFO Generated: index.html INFO Generated: archives/2021/02/index.html INFO Generated: js/script.js INFO Generated: fancybox/jquery.fancybox.min.css INFO Generated: 2021/02/08/Hello-World-Post/index.html INFO Generated: css/style.css INFO Generated: 2021/02/08/hello-world/index.html INFO Generated: css/fonts/FontAwesome.otf INFO Generated: css/fonts/fontawesome-webfont.woff INFO Generated: css/fonts/fontawesome-webfont.eot INFO Generated: fancybox/jquery.fancybox.min.js INFO Generated: css/fonts/fontawesome-webfont.woff2 INFO Generated: js/jquery-3.4.1.min.js INFO Generated: css/fonts/fontawesome-webfont.ttf INFO Generated: css/images/banner.jpg INFO Generated: css/fonts/fontawesome-webfont.svg INFO 19 files generated in 2.08 s To serve the application, run the command: $ hexo server INFO Validating config INFO Start processing INFO Hexo is running at http://localhost:4000 . Press Ctrl+C to stop.

 Conclusion

This quick and simple introduction has shown you how to use the Hexo static site. If you need more information on how to work with Hexo, please refer to the main documentation provided below: https://hexo.io/docs

How to Authorize Users Using Google OAuth in Node.js

Open Authorization, also known as OAuth, is a protocol used to authorize a user on your website using some third-party service like Google, Github, Facebook, etc. The third-party service shares some data (name, email, profile picture, etc.) with your website and then authorizes the user on its behalf without managing the passwords and usernames for your website, and saving the users a lot of extra trouble.

 How OAuth Works

When a user clicks on “Login with Google”, it takes the user to the Google OAuth consent page. When the user agrees to the consent and authenticates his identity on Google, Google will contact your website as a third party service and authorize the user on its behalf and share some data with your website. In this way, the user can be authorized without managing the credentials for your website separately.

 Implementing Google OAuth using Node.js

Almost all the programming languages provide different libraries to implement google oauth to authorize users. Node.js provides ‘passport’ and ‘passport-google-oauth20’ libraries to implement google oauth. In this article, we will implement an oauth protocol to authorize users to use node.js.

 Create a Project on Google

The first step to implement Google OAuth is to create a project on the google developer console for your website. This project is used to get the API keys used to make requests to Google for open authentication. Goto the following link and create your project: https://console.developers.google.com .

 Configuring Google Project

After you create the project, go into the project and select “OAuth consent screen” from the left side menu. Click on the ‘create’ button and provide all the details of your project. Click “Save and Continue” to move on. Now provide the scope of your project. Scopes are the types of permissions to access the user’s data from a google account. You need to set up the permissions to get specific user data from your google account. Click “Save and Continue.” Now add the test users to the project if you want. Test users are the only allowed users who can access your web application in Testing mode. For now, we will not enter any test user and click “Save and Continue” to move on to the summary page of the project. Review your project on the summary page and save the configuration. Now we will generate credentials for our project. Select the ‘Credentials’ tab on the left side menu and click on the ‘Create credentials’ button on top to generate OAuth 2.0 Client IDs. From the dropdown menu, select ‘OAuth client ID’ and specify the type of application as ‘Web application’ and your application’s name. On the same page, we have to provide two URIs, the ‘Authorized Javascript Origins’ and the ‘Authorized redirect URIs’. The ‘Authorized javascript origins’ is the HTTP origin of your web application, and it can not have any path. The ‘Authorized redirect URIs’ is the exact URI with a path where the user will be redirected after google authentication. After entering all the required entries, click on ‘create’ to create OAuth credentials.

 Initiating Node.js Project

So far, we have created a google project to authorize users for our application using google. Now we are going to initiate the node.js project to implement oauth. Create a directory named ‘auth’ and initiate the express project. ubuntu@ubuntu:~$ mkdir authubuntu@ubuntu:~$ cd authubuntu@ubuntu:~$ npm init -y

 Installing Required npm Packages

To implement Google OAuth using node.js, we need to install some npm packages. We will use ‘passport’, ‘express’, ‘path’, and ‘passport-google-oauth20’. Install these packages using npm. ubuntu@ubuntu:~$ npm install express passport passport-google-oauth20 path

 Writing Node.js Code

First of all, we will write two simple html web pages, the one with a button, and authorize the user when clicked on the button. The second page will be authorized, and the user will be redirected to the authorized page after authorization. Create a file ‘public/index.html’. <html> <head> <title>OAuth</title> </head> <body> <a href=”/google/auth”>Authorize Here</a> </body></html> Now create a file ‘public/success.html’ with the following content. <html> <head> <title>OAuth</title> </head> <body> <h1>Authorized</h1> </body> </html> After creating web pages, now we will write code to authorize the users to use google oauth. Create a file ‘index.js’. // importing required packages const express = require(‘express’); const passport = require(‘passport’); const path = require(‘path’); const GoogleStrategy = require(‘passport-google-oauth20’).Strategy; const app = express();// defining parameters// client id is the parameter that we will get from the google developer consoleCLIENT_ID=”xxxxxxx”;// client secret will also be taken from the google developer consoleCLIENT_SECRET=”xxxxx”;// user will be redirected to the CALLBACK_URL after authorizationCALLBACK_URL=”http://localhost:8000/authorized”;// port number must be the same as defined in the developer consolePORT=8000;// configuring passport middleware app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser( function(id, done) { done(null, id);}); passport.deserializeUser( function(id, done) { done(null, id);});// following middleware will run whenever passport. Authenticate method is called and returns different parameters defined in the scope. passport.use(new GoogleStrategy({ clientID: CLIENT_ID, clientSecret: CLIENT_SECRET, callbackURL: CALLBACK_URL }, async function(accessToken, refreshToken, profile, email, cb) { return cb(null, email.id); }));// serving home page for the application app.get(‘/’, (req, res) =>{ res.sendFile(path.join(__dirname + ‘/public/index.html’));});// serving success page for the application app.get(‘/success’, (req, res) =>{ res.sendFile(path.join(__dirname + ‘/public/success.html’));});// user will be redirected to the google auth page whenever hits the ‘/google/auth’ route. app.get(‘/google/auth’, passport.authenticate(‘google’, {scope: [‘profile’, ‘email’]}));// authentication failure redirection is defined in the following route app.get(‘/authorized’, passport.authenticate(‘google’, {failureRedirect: ‘/’}), (req, res) => { res.redirect(‘/success’); });// running server app.listen(PORT, () =>{ console.log(“Server is running on Port ” + PORT)})

 Testing Google OAuth

Now our application is ready, and we can test whether it authorizes the users using google oauth. Go to the root directory and run the application. ubuntu@ubuntu:~$ node index.js Now enter the url of your application into the browser. http://localhost:8000 It shows the home page with an anchor tag. When we click on the ‘Authorize Here’, it will redirect to the google oauth page. Your application name ‘Test’ is displayed on the Google authentication page. When you authorize your account, it will take you to the authorized page.

 Conclusion

Managing usernames and passwords for different web applications is not a happy task for users. Many users leave your web application without registering their account just because they do not want to manage credentials. The authorization process on your web application or website can be simplified by using third-party services like Google, Facebook, etc. These services authorize users on their behalf, and the user does not need to manage credentials separately. In this article, we have implemented the google oauth protocol to authorize users to use Node.js.

Introduction to Making GraphQL APIs and Apps in Node.js

The communication and data transfer between the front end and backend of any application occurs through APIs (Application Programming Interface). There are many different types of APIs used to communicate between the front and back-end applications like RESTful API, SOAP API, GraphQL API, etc. The GraphQL API is a relatively new technology, and it is much faster than other types of APIs available. Fetching data from the database using GraphQL api is much faster than the REST API. While using GraphQL API, the client has control to fetch only the required data instead of getting all the details; that is why GraphQL API works faster than REST API.

 Installing Packages

We will build a node.js application using GraphQL API, so we need to install node.js and npm for this before starting the project. ubuntu@ubuntu:~$ sudo apt-get update -yubuntu@ubuntu:~$ sudo apt-get install nodejsubuntu@ubuntu:~$ sudo apt-get install npm

 Setting up Project

We will use the ‘express’ framework from node.js to build our application. Create a directory named ‘graphql’ and initiate the project. ubuntu@ubuntu:~$ mkdir graphqlubuntu@ubuntu:~$ cd graphql/ubuntu@ubuntu:~$ npm init -y

 MongoDB Setup

In our GraphQL project, we will use MongoDB as our database. MongoDB is a schemaless database and stores data in the form of key pairs. In order to install mongoDB, follow the given steps. Import the public GPG key for MongoDB. ubuntu@ubuntu:~$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add - Create the list file for mongodb. ubuntu@ubuntu:~$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list Update local repositories. ubuntu@ubuntu:~$ sudo apt-get update -y Install mongodb package. ubuntu@ubuntu:~$ sudo apt-get install -y mongodb-org Start and enable mongod.service. ubuntu@ubuntu:~$ sudo systemctl start mongod.serviceubuntu@ubuntu:~$ sudo systemctl enable mongod.service

 Installing npm Modules

For our GraphQL application, we need to install some npm packages. We will install cors, express, body-parser, mongoose, etc. ubuntu@ubuntu:~$ cd graphql/ubuntu@ubuntu:~$ npm install cors express body-parser mongoose --save To create a GraphQL api, we need to install an extra npm package named ‘apollo-server-express.’ This npm package is used to run graphQL server with all Node.js HTTP frameworks like ‘express.’ ubuntu@ubuntu:~$ npm install apollo-server-express --save

 Defining MongoDB Schema

Now we have our environment set up for our GraphQL application in Node.js, and it is time to define a schema for our application. Create a file ‘models/student.js’ in the project root directory. // defining student schemaconst mongoose = require(‘mongoose’);const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, class: { type: Number, required: true }, major: { type: String, required: true }}, { timestamps: true});const Student = mongoose.model(‘Student’, studentSchema); module.exports = { Student, studentSchema } In the above-defined schema, every student must have a name, class, and major.

 Building GraphQL API

After creating the Student schema, we will now build GraphQL API. Create a ‘schema.js’ to write GraphQL parameters. There are two parameters, ‘types’ and ‘resolvers,’ used in GraphQL API. In ‘types,’ we will specify our schema, the queries (e.g., Making GET requests), and mutations (e.g., Making UPDATE or DELETE requests) to the specified schema. We will write the different methods defined in ‘types’ to link the queries and mutations with the database in ‘resolvers.’ // importing schema and moduleconst { gql } = require(‘apollo-server-express’);const Student = require(‘./models/student’).Student;// Defining Schema, Query, and Mutation Typeconst typeDefs = gql ` type Student { id: ID!, name: String!, class: Int!, major: String! } type Query { getStudents: [Student], getStudentById(id: ID!): Student } type Mutation { addStudent( name: String!, class: Int!, major: String! ): Student updateStudent( name: String!, class: Int!, major: String! ): Student deleteStudent( id: ID! ): Student }`// Defining Resolversconst resolvers = { Query: { getStudents: (parent, args) => { return Student.find({}); }, getStudentById: (parent, args) => { return Student.findById(args.id); } }, Mutation: { addStudent: (parent, args) => { let student = new Student({ name: args.name, class: args.class, major: args.major }); return student.save(); }, updateStudent: (parent, args) => { if(!args.id) return; return Student.findOneAndUpdate({ _id: args.id }, { $set: { name: args.name, class: args.class, major: args.major } }, { new: true }, (err, Student) => { if(err) { console.log(err); } else {}; }) } }} module.exports = { typeDefs, resolvers}

 Creating GraphQL API Server

Now we are almost done creating the GraphQL Application. The only step left is to create the server. Create a file named ‘app.js’ to configure server parameters. // importing required packagesconst express = require(‘express’);const mongoose = require(‘mongoose’);const bodyParser = require(‘body-parser’);const cors = require(‘cors’);const { ApolloServer } = require(‘apollo-server-express’);// importing schemaconst { typeDefs, resolvers }= require(‘./schema’);// connecting to MongoDBconst url = “mongodb://127.0.0.1:27017/students”;const connect = mongoose.connect(url, { useNewUrlParser: true }); connect.then((db) => { console.log('Connection Successful');}, (err) => { console.log(err);});// creating serverconst server = new ApolloServer({ typeDefs: typeDefs, resolvers: resolvers});const app = express(); app.use(bodyParser.json()); app.use(‘*’, cors()); server.applyMiddleware({ app }); app.listen( 8000, () =>{ console.log('listening to 8000');})

 Testing the GraphQL API

We have our graphQL server up and running on port 8000, and it is time to test the GraphQL API. Open the GraphQL webpage in the browser by visiting the following url. http://localhost:8000/graphql And it will open the following webpage. Add the student to the database using graphQL API. Similarly, add more students, and after adding the student, get all the students using GraphQL API. Note the ID of any of the Students and get the specific student using its id.

 Conclusion

Fetching data from the database using the standard REST API makes the query slow as sometimes we get more data than required. Using GraphQL, we can fetch exactly the required data that makes the GraphQL API faster. In this demo project, we only have a single schema, so we have created GraphQL API for that single schema. Also, we have defined three to four methods for the schema. You can create more than one query or mutations according to your application.

How to Deploy GraphQL Application Using Node.js on EC2 Server

GraphQL, also known as Graph Query Language, established and maintained by Facebook, is a query language used for APIs. It is built using JavaScript, Scala, Java, and Ruby programming languages. Its basic purpose is to ask for the data from server to client.GraphQL aggregates the data from different sources. Aggregation is the process of filtering data on the server side and then sending the filtered data to the client. Without aggregation, we send all the data to the client, and then the data is filtered at the client-side. This makes the system slow, and we can improve the efficiency of an API by using GraphQL. Here we will learn to deploy a simple GraphQL application using node.js on an EC2 server.

 Installing Required Packages

The first step to deploy your graphQL application is to ready your server by installing the required packages. Log in to the server using SSH. ubuntu@ubuntu:~$ ssh ubuntu@IPAdress -i KeyPair.pem NOTE: Make sure the security group of the instance is configured to allow connection from port 22 and the private key file has 400 permission. Update Ubuntu repositories. ubuntu@ubuntu:~$ sudo apt-get update -y Now install node.js and npm on your ubuntu server. ubuntu@ubuntu:~$ sudo apt-get install nodejs -yubuntu@ubuntu:~$ sudo apt-get install npm -y Verify the installation by checking the version of node.js and npm. ubuntu@ubuntu:~$ node -vubuntu@ubuntu:~$ npm -v

 Move GraphQL Application to EC2 Server

The EC2 instance is ready to deploy graphQL applications in node.js. Now we will move our code to the EC2 instance. Two common ways to copy the code to the server are listed below and will be discussed here. Copy code using scp command Clone application code from Github, Gitlab, or Bitbucket

 Copy Application Using scp Command

In order to copy your application to the EC2 server using the scp command, First of all, remove the ‘node_modules’ directory from your graphQL application. This directory has all the npm packages required to run the application. We will install these packages later before starting the graphQL application. Now compress the project directory into a zip file. After creating the zip file, we will move the project zip file to the server. Linux and windows have different methods to create a zip file.

 Windows

In windows, right-click on the application root directory and go to the ‘send to’ option. It will open a submenu. Click on the ‘Compressed (zipped) folder’ to create a zip file of the graphQL application.

 Linux or Mac

In Linux or Mac OS, we will use the ‘zip’ command to create a zip file of the project. ubuntu@ubuntu:~$ zip -r graphQL.zip graphQL The above command will generate the graphQL.zip file of the graphQL directory.

 Upload Application to the Server

Now we have a zip file of our application, and we can upload the zip file to the server by using the scp command. ubuntu@ubuntu:~$ scp -i KeyPair.pem graphQL.zip ubuntu@IPAddress:~/ The above command will move the project zip file to the remote server’s home directory over the ssh connection. Now on the remote server, unzip the project zip file. ubuntu@ubuntu:~$ unzip graphQL.zip Clone Application From Github, Bitbucket or Gitlab The second method to copy application code to the server is using git. Install git from the command line on the EC2 server. ubuntu@ubuntu:~$ sudo apt install git Check the git version to verify the installation. ubuntu@ubuntu:~$ git --version If it does not give the version of git, then git is not installed. Now clone the application from the github, gitlab, or bitbucket. Here we will clone the application code from the github. ubuntu@ubuntu:~$ git clone ttps://github.com/contentful/the-example-app.nodejs Starting the GraphQL Application Now we have our graphQL application on the remote server. Go to the root directory of the graphQL application and install the required npm packages to run the graphQL application. ubuntu@ubuntu:~$ cd graphQLubuntu@ubuntu:~$ sudo npm install This command will analyze the package.json file in the project and install all the required npm packages. After installing the required packages, now we will start the graphQL application. ubuntu@ubuntu:~$ node app.js

 Running Application as Daemon

When we run the application using the standard method as described above, it runs in the foreground, and the application stops when you close the terminal window. We can run the application as a background process by appending the ampersand (&) sign to the command. ubuntu@ubuntu:~$ node app.js & The problem with this method is that when we modify our application code, the applied changes will not reflect automatically. We will have to restart the application every time we modify the code to apply the changes. In order to run the application in the background and to apply changes automatically, we will use an npm package named pm2. Install pm2 on the server. ubuntu@ubuntu:~$ sudo npm install -g pm2 Start the graphQL application using pm2. ubuntu@ubuntu:~$ pm2 start app.js --name “graphQL” --watch The ‘–name’ flag will name the background process, and we can start and stop the application using the name. The ‘–watch’ flag will go on checking the application code to apply changes immediately. You can learn more about pm2 by visiting the following link https://pm2.keymetrics.io/

 Querying GraphQL API from Browser

We can configure our graphQL application to make graphQL queries from the browser manually. For this, we have to create a separate HTTP endpoint on which we will mount the graphQL API server. And this HTTP endpoint will be used to make manual queries. Following is the code to create the graphQL api server endpoint. const express = require(‘express’); const { graphqlHTTP } = require(‘express-graphql’); const { buildSchema } = require(‘graphql’); const graphQLSchema = buildSchema(` type Query{ message: String }`); const func = { message: () => { return ‘you are using graphql api server’; }}; const server = express(); server.use(‘/graphql’, graphqlHTTP({ schema: graphQLSchema, rootValue: func, graphiql: true})); server.listen(3000); Now, after running the server, we can access the graphQL api server on the following route. http://localhost:3000/graphql

 Querying GraphQL API Using CLI

In the previous section, we made graphQL queries from the browser using graphiql. Now we are going to make graphQL queries using the command-line interface in ubuntu. From the command line, to make an HTTP POST request, we will use the curl module. ubuntu@ubuntu:~$ curl -X POST -H "Content-Type: application/json" -d '{"query": "{ message }"}' http://localhost:3000/graphql

 Querying GraphQL API Programmatically

In order to make graphQL query programmatically, we will use the ‘node-fetch’ module in node.js. Open node.js in the terminal. ubuntu@ubuntu:~$ node Now make the HTTP POST request to the server using the ‘node-fetch’ module. GraphQL is an efficient query language, and it can decrease the response time of a query made to the database. The standard api calls to fetch data from the database involve many unuseful data in the response, and hence response time increases, which decreases the efficiency. The query made to the databases using GraphQL returns only the useful data and hence decreases the response time. In this article, we have deployed our graphQL application on an EC2 instance.

WebSocket Example Program

The WebSocket protocol allows for two-way communication to occur between a client and a server. This process is similar to the way in which calls on your phone take place: first, you establish a connection, and then you can start communicating with one another. The WebSocket protocol is used almost everywhere – from multiplayer browser games to chat applications. This article shows you how to create a WebSocket protocol and use it to communicate with multiple users.

 Prerequisites

Before moving on to the process of creating and using a WebSocket protocol, you first need to install a few things that are required for this process. The first thing that you need to install is Node.js, a server-side platform that converts the JavaScript programming language into machine code that allows you to run JavaScript directly on your computer. To install Node.js, Windows users can simply go to the official Node.js website and click on the green LTS button found in the center of the screen. For Linux and macOS users, click on the Downloads section in the sub-header of the website. After opening the Downloads section, you will see installation files for all three major platforms. Select a package that is supported by your system. Run the installer that comes with the downloaded files, and Node.js will be installed on your computer. To check whether the program has been installed, open the terminal and issue the following command: $ node -v After installing Node.js, you now have access to various JavaScript modules, which will make your work more efficient in the long run. Open the directory in which you want to create your client and server architecture, then open the terminal inside that directory and run the following command: $ npm init -y This command is used to create the package.json file that allows you to set up and install different Node.js packages. Install the WebSocket protocol package by issuing the following command in the terminal: $ npm install ws Create three files, called index.html, client.js, and server.js. As indicated by the names, these JavaScript files are the client and server architecture of our WebSocket protocol. Now, we can finally start writing the code of our client and server applications.

 Creating a WebSocket Server

To create a WebSocket server, we will start by writing the code for the server. Open the server.js file that you created inside your text editor or IDE in the previous section and enter the following lines inside the file. const WebSocket = require('ws');const ws = new WebSocket.Server({ port: 8080 }); console.log("Server Started"); ws.on('connection', (wss) => { console.log("A new Client Connected") wss.send('Welcome to the Server!'); wss.on('message', (message) => { console.log(`Server Received: ${message}`); wss.send('Got your Message: ' + message); });}); Now, we will explain what each line is doing in greater detail.

 Code Explanation

As mentioned previously, there are some built-in modules available in Node.js that make your work much easier. To import these modules, we will use the require keyword. const WebSocket = require('ws');const ws = new WebSocket.Server({ port: 8080 }); console.log("Server Started"); The first line is used to import the Node.js WebSocket module. Using this module, in the next line, we create our WebSocket server, which is listening on port 8080. The console.log() line is simply there to let us know that the Server has started. You will see this appear inside your terminal when you run the following command in the terminal: $ node server In the next line, we are establishing a connection between the server and the client. ws.on('connection', (wss) => { console.log("A new Client Connected")}); After a connection has been established, the wss.send() line sends a message to the client. In this case, the message is “Welcome to the Server.” wss.send('Welcome to the Server!'); Finally, the wss.on (‘message’) is for the server to receive the message from the client. For confirmation, the server sends this message back to the client in the last line. wss.on('message', (message) => { console.log(`Server Received: ${message}`); wss.send('Got your Message: ' + message); });

 Creating a WebSocket Client

For the client-side, we need both the index.html file and the client.js file. Of course, you can simply add the content from the client.js file into your index.html file, but I prefer keeping them separate. Let us first look at the client.js code. Open the file and enter the following lines inside of the file: const socket = new WebSocket('ws://localhost:8080'); socket.addEventListener('open', () => { console.log('Connected to the Server!');}); socket.addEventListener('message', (msg) => { console.log(`Client Received: ${msg.data}`);});const sendMsg = () => { socket.send('Hows it going amigo!');}

 Code Explanation

Like with the server.js, we will create a new WebSocket that is listening to port 8080, which can be seen in the localhost:8080 section of the code. const socket = new WebSocket('ws://localhost:8080'); In the next line, addEventListener makes your client listen to any events that are currently happening. In this case, it would be creating and starting the server. Once the connection is established, the client outputs a message to the terminal. socket.addEventListener('open', () => { console.log('Connected to the Server!');}); Once again, the client listens to any events currently happening. When the server sends a message, the client receives this and then displays the message in the terminal. socket.addEventListener('message', (msg) => { console.log(`Client Received: ${msg.data}`);}); The last few lines are simply a function where the client is sending a message to the server. We will connect this to a button in our html file for a better understanding of how this is working. const sendMsg = () => { socket.send('Hows it going amigo!');}

 Preparing an HTML File

Finally, open the index.html file and add a reference to your client.js file inside of it. In my case, I will simply add the following lines of code: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Client</title></head><body> <button onClick="sendMsg()">Send Message to Server</button></body><script src="client.js"></script></html> As you can see in the lines below, src (inside the script tag) refers to the client javascript file. The sendMsg function, which was created in the client.js file, has also been connected to the button’s onClick function. <button onClick="sendMsg()">Send Message to Server</button> <script src="client.js"></script>

 Putting Everything Together

You can now start testing your Client and Server Architecture. First, open the terminal and run the following command to start your server: $ node server After starting your server, open the directory in which your index.html file is present, and double-click on it to open it in your browser. You will see the following message appear in the terminal stating that a client has connected: You can also check the messages sent from the server to the client by pressing the right-click button and then opening the Inspect window. In this window, click the Console section, and you will be able to see the messages sent from the server. Once you click on the button, both the server and client will be able to send and receive messages to and from each other. Server: Client: Voilà, your WebSocket connection has been established!

 Conclusion

The WebSocket protocol is an excellent way to establish communication between a client and a server. This protocol is used in several fields, including multiplayer browser games, chat systems of various social media platforms, and even collaboration processes between coders.

Vue.js vs. Django

When you are required to choose a library or framework for building web applications, there is no question that JavaScript libraries are preferred over any other library. But that does not mean that other libraries are not good enough. Vue.js and Django are both famous JavaScript web frameworks. They are also both open-source tools. Vue.js is famous for building clean, reusable, component-based web applications. Django is a framework that is built on Python and is known for its rapid development and rational code design. In this article, we will discover some of the basic and more technical differences between Vue.js and Django. This includes the pros and cons of each framework, the companies that currently use these frameworks, integrated tools, and much more.

 Difference between Vue.js and Django

Vue.js is a front-end JavaScript framework that generates pages on the client-side. Because it renders pages on the client-side, Vue.js costs more initial load time, but it gives a better experience when it is necessary to navigate between pages. While Django is a full-stack Python framework and it generates pages on the server-side. Its server-side rendering helps in initially loading the page but while navigating we may have to face performance issues due to the network latency.

 Pros of Vue.js

Vue.js is a simple, easy-to-use, and fantastic library for your needs. You can learn it hands-on if you know Html, CSS, and JavaScript. Vue.js is a framework with a fast learning curve signature. The documentation written for Vue.js is also easy to understand and extremely detailed, as well. The documentation is so well written that you should not feel confused, even when working with it all day. All steps are explained clearly and the Vue.js documentation is one of the best guides available for any web framework. Vue.js is a complete and functional JavaScript ecosystem, and it stands as one of the top front-end frameworks.

 Pros of Django

Django is known for its rapid development, and it is an open-source tool. This framework has a great community, as well. Django is an elegant MVC Framework that helps you in writing beautiful code. This framework is free to use, has great documentation, and is very easy to learn, as well. It also provides great packages and libraries to help in development.

 Cons of Vue.js

The community of Vue.js is smaller than the other two competitive frameworks, reactJS and Angular. Vue.js does not support fragments, and it only supports multiple root nodes programmatically. Another con of Vue.js is its YXML vs. HTML markup.

 Cons of Django

Django is an underpowered templating framework and has an underpowered ORM. Its auto-reload restarts the whole server. Django’s URL dispatcher ignores the HTTP method and has some coupling of internal subcomponents. Having cons does not necessarily mean that a framework is bad. Actually, every framework comes with the intention of fulfilling some particular need or providing some specific value. It is a well-known fact that every framework has its own features and standards that differentiate it from other frameworks, and it is easy to prioritize one over another according to your needs.

 Companies that Use Frameworks

Both of these frameworks are backed by good companies. Vue.js is backed by a lot of big names, such as: Alibaba Xiaomi Laracast Trivago.com Django is also backed by some big names, such as: Pinterest Instagram Udemy Robinhood

 Conclusion

In this article, we reviewed both the Vue.js and Django frameworks and pointed out their differences. We also discussed the pros and cons of each framework and mentioned the name of the companies backed by these frameworks. Vue.js is becoming quite popular among JavaScript frameworks and front-end web development at an increasing pace, specifically in terms of single-page applications and user interfaces. Meanwhile, Django will have its own recognition of being a full-stack and rapid development framework.

Vue.js Router

Vue.js is a reactive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications) and developers love to code and feel freedom and comfort while developing applications in Vue.js. For routing purposes, Vue.js does not provide the built-in routing feature. But there is an official third party library with the name of Vue Router for providing this feature. By using this feature we can navigate between the web pages but without reloading. So, in this article, we are going to see how we can install and use Vue Router in Vue.js.

 Installation

We can install the Vue router into an existing Vue.js project by running the following command in the terminal npm install vue-router After a successful installation, we need to import VueRouter in the main.js file in the src directory as well using the following syntax import Vue from 'vue'import router from './router' Vue.use(router) After importing the router, you are good to go and use vue-router in your project. But if you are installing Vue.js using Vue CLI. You won’t need this extra installation step. You can add a vue-router plugin during selecting a preset.

 Usage

The usage of the vue-router is very simple and easy to use. First, in the template or HTML <template><div id="nav"><router-link to="/">Home</router-link> |<router-link to="/about">About</router-link></div><router-view /></template> In this pretty simple and clear example of vue-router. We have created simple navigation using router-link components and provide the link using the prop named ‘to’. The router-link works the same as an anchor ‘a’ tag. It is actually rendered as an ‘a’ tag by default. In the router-view, we will have the relative component which matches the route. In the javascript, we first have to register and import the components to define their routes. We suppose that we have a component named Comp.vue in the views directory to which we will import in the router’s index.js file in the router directory and define it as a route. To import a component, we use the following statement import Comp from "../views/Comp.vue"; After importing, we have to define the route now and map it to the component. Like this, const routes = [{ path: "/", name: "Comp", component: Comp}]; We can give multiple routes too, separated by a comma. Like this, const routes = [{ path: "/", name: "Comp", component: Comp},{ path: "/comp2", name: "Comp2", component: Comp2}]; After defining the routes. Pass routes array to the router instances. So, let’s create the router instance as well const router = createRouter({ routes // short for `routes: routes`}); In the end, in the main.js file. We have to create the root instance and mount that as well and inject the routes in it so that the whole app becomes aware of the routes. createApp(App) .use(router) .mount("#app"); By using this injection technique. We can access the router in any component, using this.$router. We can now programmatically push routes at the click of a button or anything you want, instead of using the router-link component. For example, methods: { clickFunc() {this.$router.push('/about')}}

 Wrapping up and summary

In this article, we have learned to install Vue Router using different ways and learned to use Vue router programmatically and in the Vue.js’s template. We have also learned to set up the Vue Router in an existing project in a very easy and step by step detailed guide. If you want to learn more about the Vue Router, kindly visit Vue Router: Official Docs.

Vue.js Emit Custom Events

Vue.js is a versatile and full-fledged framework for building huge web applications. Any web application is divided into the Components. For example, a simple website that includes a header, sidebar, and some other components. In order to manage and handle this component-based approach, Vue.js offers the parent-child relationship between the components and if we want to send some data across components. Vue.js offers props to send data from the parent to a child component but to send data from the child to the parent; we have to emit custom events. In this article, we learn about firing and listening to custom events.First of all, let’s see how to fire a custom event in Vue.js and then how to listen to that event. The syntax for firing an event in Vue.js is this.$emit('eventName') In this syntax, we need to be careful while giving a name to the event because using the same name; we will later listen to this event. In order to listen to this event, we can listen to it as we listen to a click event in Vue.js. For example <myComponent @eventName="doSomething"></myComponent> We can write any expression in the inverted commas as well as a function. So let’s try an example to better understand it.

 Example

Suppose we have a Component named “parentComponent,” which includes a child component in it with the name of “childComponent” to which we are passing a message using props. <template><h1>Parent Component</h1><div><h2>Child Component</h2><ChildComponent msg="Hello Child" /></div></template><script>import ChildComponent from './components/ChildComponent.vue'export default { name: 'ParentComponent', components: { ChildComponent}}</script> In the child Component, we are getting props and showing the message in the ‘p’ tag. <template><p>{{ msg }}</p></template><script>export default { name: "ChildComponent", props: { msg: String}}</script> Now after having these two components set up. Let’s say hello back to our ParentComponent. In order to say hello back, we will first create a button, and at the click of that button, we will call the “helloBack” function. After creating the button, the child component’s HTML would be like this <template><p>{{ message }}</p><button @click="helloBack">Send Hello Back</button></template> Let’s create the “helloBackFunc” function in the methods object as well. In which we will emit the “helloBackEvent” along with a “helloBackVar” variable that contains the string “Hello Parent”. After creating a function, the javascript of the child component would be like this <script>export default { name: "ChildComponent", props: { msg: String}, data(){return{ helloBackVar: 'Hello Parent'}}, methods:{ helloBackFunc(){this.$emit('helloBackEvent', this.helloBackVar)}}}</script> We are done with firing the event. Now, let’s move to the parent component for listening to the event. In the Parent component, we can simply listen to the event, just like we listen to the click event. We will simply listen to the event in the ChildComponent’s tag and calls the “thanks()” function on it. <ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" /> In the thanks function, we will assign the passed string to the variable named “thanksMessage”. After creating the function and assigning the passed string to the variable, the javascript of the “parentComponent” would be like this <script>import ChildComponent from './components/ChildComponent.vue'export default { name: 'App', components: { ChildComponent}, data(){return{ thanksMessage: ''}}, methods: { thanks(m){this.thanksMessage = m;}}}</script> And bind the “thanksMessage” variable in the template somewhere to see either it works or not. <template><h1>Parent Component</h1><p>{{ thanksMessage }}</p><div><h2>Child Component</h2><ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" /></div></template> After creating and writing all this code, go to the web page and reload it to get the latest functionalities. We can see that the props are conveyed successfully to the child component. Now, if we click the button, which is actually in the child component. The thanks message should be displayed right after the parent Component Heading. As you can see, it is displayed. So, this is how we can emit or fire the custom events and listen to them in some other component in Vue.js.

 Summary

In this article, we have learned to emit custom events in the Vue.js. This article contains a step by step proper example to understand it with a brief explanation along with it. So, we hope this article helps in having better and clear concepts of emitting custom events in Vue.js. For more such useful content, keep on visiting linuxhint.com

What is Vue.js, and Why is it Cool?

Vue.js is a progressive JavaScript framework, which is used to build UIs (User Interfaces) and SPAs (Single-page Applications). This framework is famous for its fast-paced learning curve. It is such an easy to learn and approachable library that with the knowledge of HTML, CSS, and JavaScript, we can start building web applications in Vue.js. The fast learning curve is kind of a signature of this framework. It is a versatile framework for our need as a library or a full-fledged framework for building huge web apps. Evan You have created this framework. The idea of Evan You behind this framework is to build the best framework by combining the best features from already existing Angular and react Frameworks. Before building Vue.js, Evan You was working at Google. Inc and worked on Angular based projects. So, he came up with the idea of building his own framework. He picked the best parts of Angular, like template syntax, easy to use, and picked the best parts of React as well, like two-way data binding, the concept of props, component-based approach, and combined them to make a new framework Vue.js better than both of them.

 Competition

Every framework has its own features and characteristics, because of which they are known and get priority over any other framework. Vue.js has a record of having the most stars at Github.com for the past 5 years. Although the community of Vue.js is smaller than the react JS, Vue.js stars record is describing and telling about the fans of Vue.js. Whoever uses it once, he/she falls in love with it.

 Evolution and Growth

Vue was released way back in 2014. Since then, it is continuously evolving. At the beginning of 2018, Vue.js started beating Angular and becoming more famous in the market. Later, in September 2018, Evan You decided to announce the release of Vue 3.0. Vue.js is continuously evolving with the rapid growth in the usage and community of this framework. The community will keep growing because it was built on the best features combination of Angular and React. Here are some of the features that we find exciting and the root cause of its rapid growth and make it cool.

 Learning Curve & Well written Documentation

Vue.js has one of the best-written Documentation that we have ever seen and suggested. This Documentation takes us through an effortless and step by step guide that one doesn’t feel like hard learning or something different is happening. The learning curve is effortless if we compare it with the react.JS and Angular.

 Modular and reusable code

This component-based approach was basically inspired by and picked from the ReactJS. We write code in the form of components to import that component and reuse it wherever we need it. Vue.js offers a single-file component, which makes it a loosely coupled and reusable code.

 Mobile Development

There is one underrated feature of Vue.js, which is its cross-platform mobile development. Yes, just like react-native works for react.JS. Vue.js has WEEX developed by Alibaba, Native Script, and Ionic to help in developing mobile UIs. Native Script and WEEX claim that you just have to write the code once and then use/run it wherever you want.

 Easy Development

Developers love to code or build applications in Vue.js. They feel freedom and comfort while developing in an unopinionated environment. Vue.js offers the best component-based approach like whatever a developer needs; he can find it in a single .vue file. Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component.

 Ecosystem for Development

Vue.js has a very active and vibrant community, which is helping a lot in evolution and growth. Vue.js provides a lot of different tools and libraries to facilitate the development process. The community has some remarkable and note tools and libraries that a coder or developer demands. For example, Vue Router is used for any type of routing. Vuex is used as a centralized store for state management.

 Summary

Vue.js is an easy, fast-growing, and adaptable framework to implement in developing applications that anybody with the basic knowledge of web development can get started with because of its invisible learning curve and easy to understand Documentation. Vue.js provides a full-fledged ecosystem, and it is counted in the top 3 JavaScript front-end frameworks. Honestly, it is the best framework it can be. It is backed by a lot of big names like Alibaba, Xiaomi, and Lara cast. So, it is a must-try framework if you have not tasted it yet.

Vue.js Conditional Rendering

Vue.js is an easy to learn and approachable library that we can start building web applications in it with the basic knowledge of web development. In Vue.js, developers love to code and feel freedom while developing applications. In any dynamic web application, conditional rendering is a necessary part. Vue.js provides different ways for conditional rendering, and we can use any of the following ways which suit our purpose: v-show v-if v-else In this article, we will try these directives provided by Vue.js for conditional rendering and understand them in a better way.

 v-show

The v-show only hides the element by disabling its visibility. It hides the element if the value of the passed expression or variable is not truthy. For example: <p v-show="isBool">This paragraph is not hidden</p><p v-show="!isBool">This paragraph is hidden</p>

 v-if

On the other hand, v-if does not hide the element, but it also does not render anything until the value of the passed expression or variable becomes true. For Example: <!-- This div is conditionally rendering --> <div v-if="isBool"> <p>This is a paragraph</p> </div> There is an additional feature in the v-if directive as compared to the v-show directive. We can apply it to the template block as well if we do not want to render anything in between that block. Either there is a child component in that or a lot of other elements. For example: <!-- This template is conditionally rendering --> <template v-if="isBool"> <h1>This is a Heading</h1> <p>This is a paragraph</p> <!-- A child component --> <Hello msg="Hello Vue" /> </template>

 v-else

We can also use the v-else directive along with the v-if statement in order to conditionally render between any of the two blocks. But, keeping in mind that the v-else block must have to appear right after the v-if block. For example: <p v-if="isVar == true">This paragraph will render if 'isVar' becomes true</p> <p v-else>Else, this paragraph will get rendered.</p> We can apply v-else on the template block as well. <!-- This div is conditionally rendering --> <div v-if="isVar == true"> <h1>This is a Heading</h1> </div> <!-- v-else on template block --> <template v-else> <p>This is a paragraph</p> <!-- A child component --> <Hello msg="Hello Vue" /> </template>

 v-else-if

Just like v-else, we can also use the v-else-if directive along with the v-if directive. For example: <div v-if="type == 'car'"> <p>Car</p> </div> <div v-else-if="type == 'book'"> <p>Book</p> </div> <div v-else-if="type == 'animal'"> <p>Animal</p> </div> <div v-else> <p>None of the ablove</p> </div>

 v-if vs. v-show

The v-if and v-show kind of do the same task. They both hide the elements in the DOM based on the truthy or falsy value of the passed expression, but with a subtle difference of hiding and not rendering elements. If we compare the time and processing cost between these two. The v-if costs more during runtime or toggling, while v-show costs more at the start of rendering. So, it would be wise to use v-show when toggling is purpose. Otherwise, v-if is preferred.

 Wrapping up

In this article, we have learned how to conditionally render the DOM in Vue.js using v-if and v-else directives. We have shown some examples and learned about the real difference between v-show and v-if directive. If this article helps you to have a better understanding and concepts, keep on visiting linuxhint.com for such useful content.

Vue.js Change Style

Vue.js is used to build User Interfaces (UIs) and Single-Page Applications (SPAs). It is easy to learn how to use Vue.js and the framework of freedom and comfort that is available while developing applications in this program because it has the best-combined features of Angular and ReactJS. That is why it is known for its easy-to-use and clean coding. Vue.js provides style binding that you can use to change the style dynamically. You can bind a variable to the style attribute in any HTML tag and change the style when the bound variable is changed. In this article, we will have a look at how to use style binding and change the styling of variables using vue.js.

 Inline Style Binding

In vue.js, we can bind variables to style attributes using v-bind directives.

 Object Syntax

Just like with inline CSS styling, we can also do inline styling in Vue.js using v-bind directive and curly braces object syntax. You can bind any variable to the style attribute using the following script: <p :style="{ color: colorVar, fontSize: fontSizeVar + 'px' }"></p> And, in the script tag and data: ata() { return { colorVar: 'red', fontSize: 14 }} We can also take the object down to the data and bind that object with the style attribute to make our HTML look cleaner as follows: data() { return { styleObject: { colorVar: 'red', fontSize: 14 } }} Now, we will bind the “styleObject” variable to the style attribute as follows: <p :style="styleObject"></p>

 Array Syntax

Vue.js also provides the option to bind multiple variables in array syntax to the single HTML tag, as follows: <p :style="[basicStyling, extraStyling]"></p>

 Multiple Values

Similarly, we can also give multiple values using the array syntax to a CSS property within the inline binding, as follows: <div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div> These are some of the different ways that we can use for binding variables with the style attribute to dynamically change the styling of a webpage.

 Summary

This article covered the syntax for binding inline styling. You also learned about the object syntax and array syntax used to bind the values or variables to style attributes in vue.js. If this article proved helpful in giving you a better understanding of vue.js, feel free to continue reading at linuxhint.com for more useful content.

Vue.js Click Events

Vue.js is a very powerful, easy to learn, and approachable library that with the knowledge of HTML, CSS, and Javascript, we can start building web applications in it. Vue.js is built by combining the best features from already existing Angular and react Frameworks. It is a progressive and reactive Javascript framework that is used to build UIs (User Interfaces) and SPAs (Single-page Applications), which is why the developers love to code and feel freedom and comfort while developing applications in Vue.js.If we take a look at the Event Listening and Handling in Vue.js., we will know that it provides a “v-on” directive to listen and handle events. We can use the “v-on” directive to listen to the DOM and perform the required tasks. It also provides many event handlers. However, in this article, we will only learn and keep our focus on the click events. So, let’s get started! Just like Javascript’s onClick event, Vue.js provides v-on:click for listening events. The syntax for v-on:click event would be like this: <button v-on:click="functionName">Click</button> Vue.js provides a shorthand “@” instead of using “v-on” as well. <button @click="functionName">Click</button> Vue.js doesn’t stop in just listening to the click event and calling the function. It will also allow us to directly write any arithmetic operation or anything related to Javascript inside the quotation marks “ ”. Just like this: <button @click="num += 1">Add</button> Vue.js provides us to call the method or function in an inline Javascript statement, as shown below: <button @click="message('Hi')">Show</button> Using Vue.js’s event handlers, we can access the DOM event as well, using inline statement, by passing the Vue.js’s especially provided “$event” variable into the method’s argument, just like the example below: <button @click="message('Hi', $event)">Send</button> Vue.js also provides us to call multiple functions or methods. We can call more than one function and separate them by commas, like this example: <button @click="first('Hello'), second('Hi', $event) ">Submit</button> Vue.js provides event modifiers as well.

 Event Modifiers

We often need to call modifiers along with the events. So, Vue.js provides some of the following modifiers: .stop It will stop the click event’s transmission. <a @click.stop="doThis"></a> .prevent It will prevent the page to reload or redirect. <form @submit.prevent="onSubmit"></form> .once It will trigger the click event only once. <a @click.once="doThis"></a> .capture It is mostly used to add the event listener. <div @click.capture="doThis">...</div> We can chain the modifiers as well. However, keep in mind that the order of modifiers does matter, and it will affect the results. <a @click.stop.prevent="doThat"></a>

 Conclusion

In this article, we have covered the whole Click event handling concepts from noob to ninja level. We have learned about the different syntaxes of writing click events and the different ways to use v-on:click directive provided by Vue.js for the ease of developers and different event modifiers. For more useful content like this, related to Vue.js, keep on visiting linuxhint.com.

Vue.js Components

Vue.js is a progressive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications). We can start building web applications in Vue.js with the basic knowledge of HTML, CSS, and Javascript. Vue.js is built by combining the best features from already existing Angular and react Frameworks. Developers love to code and feel freedom and comfort while building applications in Vue.js. This component-based approach was basically inspired by and picked from the ReactJS. We write code in the form of components so that we can import that component and reuse it wherever we need it. Vue.js offers a single-file component, which makes it a loosely coupled and reusable code. Vue.js offers the best component-based approach, like whatever a developer needs; he can find it in a single .vue file. Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component. In this article, we will have a look at the single-file component, which has a .vue extension. So, let’s have a look at a very simple Vue component example and understand it. <template> <p>{{ message }} World</p></template><script>export default { name: "hello", data(){ return{ message: "Hello" } }}</script><style> p { font-size: 1em; text-align: center;}</style> This a very simple and basic example of a Vue component. In which we can see that the code is divided into three layers. This three-layer syntax is the best part of Vue.js. It satisfies the separation of concern yet being in one single .vue file. We have our template(HTML), logic, and styling inside a component. Template Script Style

 Template

In this template tag, we write our HTML code. We can bind variables in this as well using the Vue.js data-binding syntax, and we can add some other functionalities in this as well using the Vue.js provided syntax for the respective functionalities.

 Script

This is the section where we can write the logic of the component by following the syntaxes of Vue.js. All the functionalities and logic of a component go here. For example, Importing other components and packages needed. Variable declaration Methods/Functions Life cycle hooks Computed properties and watchers And so on…

 Style

This is where we write the styling in CSS of the component, or we can use any preprocessor we want to use. This is just a glimpse of a component in Vue.js. Let’s take a look at the usage, organization, and data flow between components a little bit.

 Import and Use Components

To use the component, we first have to import the component. Otherwise, how can Vue.js know about it? We can simply import a component by adding an “Import” statement at the beginning of the script tag and declaring that component in the “components” object, using the following syntax. <script>import Hello from './components/Hello.vue'export default { name: 'App', components: { Hello }}</script> After importing the component successfully, we can use it in the template like this <Hello msg="Hello Vue" /> This is how simply we can import and use a component in any other component.

 Organizing Components

Just like any other application, the Components organization goes like a nested tree. For example, a simple website that includes a header, sidebar, and some other components in a container. The organization of the component would be like this. Image from Vue.js Official Docs

 Data Flow between Components

There can be two types of data flow between components: Parent component to Child Component We can send data from the parent component to the child component using props: Child Component to Parent Component We can send data by emitting an event from the Child component and listen to it on the other end (Parent component).

 Wrapping Up

In this article, we have gone through a whole journey of understanding a basic component in Vue.js to its usage, its hierarchy, its organization, and implementation of Importing, using, and know-how about communication between components. This article covers a lot of scope of components, yet there is a lot of in-depth knowledge about components out there. So, feel free to visit the Vue.js Official Docs for more information.

Vue.js Data Binding

Vue.js is such an easy to learn and approachable library. So, with the knowledge of HTML, CSS, and Javascript, we can start building web applications in Vue.js. Vue.js is built by combining the best features from an already existing Angular and react Frameworks. Data binding is one of the most elegant features of Vue.js because it provides reactive/two-way data binding. In Vue.js, we do not have to write a lot of lines to have two-way data binding, unlike other frameworks. One-way data binding means that the variable is just bound to the DOM. On the other hand, two-way means that the variable is also bound from the DOM. When DOM gets changed, the variable also gets changed. So, let’s take a look at both of the data bindings and see the right difference.

 One-way Data Binding

If we want to bind any variable, we can simply use Vue.js’s double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance. <p> {{ linuxhintText }} </p> Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive. <div v-bind:class="container"></div> Vue.js also provides the shorthand for binding variables in an HTML attribute. Instead of writing v-bind:attribute-name, we can only use a colon “:” and attribute name. <div :class="container"></div> But these are just data bindings. To demonstrate the two-way data binding, we can use the v-model directive provided by the Vue.js.

 Two-Way/Reactive Data Binding

In order to demonstrate reactive data binding, we can use the v-model directive on an input form field. It will internally emit an event and change the variable. To which we can bind somewhere else in the template using Double curly braces or “Mustache” syntax. <input v-model="linuxhintText" placeholder="Type something" /><p>You are typing: {{ linuxhintText }}</p></td> Now, whenever we enter a character in the input form field, we can see that the variable is also updating simultaneously.

 Wrapping up

In this article, we have learned how to bind variables in Vue.js using double curly braces or “Mustache” syntax. We have also demonstrated the two way/reactive data binding in Vue.js using the v-model directive. After reading this article, data binding is not a difficult task anymore for a beginner who has just got a start with Vue.js. So, keep on learning the concepts of Vue.js with linuxhint.com. Thank you!

Vue.js Watch Property

Vue.js is a very powerful and reactive Javascript framework, which is used to build Uis (User Interfaces) and SPAs (Single-page Applications). It is built by combining the best features from already existing Angular and react Frameworks. Developers also love to code or build applications in it. Vue.js provides the watch property to observe and react to the variables or data change. We can use the watch property to manipulate the DOM when the watched variable gets changed. In this article, we are going to have a look at how we can use watch property, and perform the desired tasks on the change of variable. So, let’s get started.

 Watchers

A watcher in Vue.js acts like an event listener to a variable or property. It is used to accomplish several tasks on the change of some specific property. It comes in handy while doing asynchronous tasks. Let’s demonstrate and understand the concept of the watcher by considering an example.

 Example:

Suppose we are building an e-commerce website, in which we have a list of items, and we are building it cart or checkout component. In that component, we need to calculate the amount of a single element concerning the number of items. First, we are assuming some properties in the data. data() { return { itemName: "Item 1", itemQuantity: null, itemPrice: 200, totalPrice: 0 }}, In which we will watch the “itemQuantity” property and calculate the total price. We will first do the data bindings in the template, before writing the code for watching the variable and calculating the total price. <template> <h1>Watcher</h1> <p>Item Name: {{ itemName }}</p> <p>Item Price: {{ itemPrice }}</p> <input type="number" v-model="itemQuantity" placeholder="quantity" /> <p>Total Price: {{ totalPrice }}</p></template> After writing this code, we will have our web page like this: Now, we want to change the total price on the change of “itemQuantity” like whenever the user changes the quantity using the input field. The Total Price should get changed. For that purpose, we will have to watch the “itemQuantity” and calculate the total price whenever the “itemQuantity” property gets changed. So, the watcher for the “itemQuantity” would be like this: watch:{ itemQuantity(){ this.totalPrice = this.itemQuantity * this.itemPrice; console.log(this.itemQuantity); }} Now, whenever the user changes the “itemQuantity”, the total price will be changed in a moment. We don’t have to worry about anything, anymore. The watch property will take care of this calculation now. Let’s have a look at the web page: And, let’s try to increase or change the quantity and see some results: If we change the quantity, let’s say “4”, the total price would be “800”: Similarly, if we change the quantity to “7”, the total price would be “1400”: So, this is how the watch property works and helps in reactive development. Reactivity is kind of a signature of Vue.js. Also, the watch property comes in handy while performing asynchronous operations.

 Conclusion

In this article, we have learned what is a watch property and how we can use it in Vue.js. We have also tried a real-life example to understand its true implementation. This helps a lot in saving time and speeding up the development process. We hope that you found this article helpful and keep on visiting linuxhint.com for better understanding.

Setup Electron and Create Hello World Application in Linux

This article will cover a guide about installingElectronand creating a simple “Hello World” Electron application in Linux.

 About Electron

Electron is an application development framework used for creating cross-platform desktop applications using web technologies in a standalone web browser. It also provides operating system specific APIs and a robust packaging system for easier distribution of applications. A typical Electron application requires three things to work: Node.js runtime, a standalone Chromium based browser that comes with Electron and OS specific APIs.

 Install Node.js

You can install Node.js and “npm” package manager by running the following command in Ubuntu: $ sudo apt install nodejs npm You can install these packages in other Linux distributions from the package manager. Alternatively, download official binaries available on Node.jswebsite.

 Create a New Node.js Project

Once you have installed Node.js and “npm”, create a new project named “HelloWorld” by running the following commands in succession: $ mkdir HelloWorld $ cd HelloWorld Next, fire up a terminal in the “HelloWorld” directory and run the command below to initialize a new package: $ npm init Go through the interactive wizard in the terminal and enter names and values as needed. Wait for the installation to finish. You should now have a “package.json” file in “HelloWorld” directory. Having a “package.json” file in your project directory makes it easier to configure project parameters and makes the project portable for easier shareability. The “package.json” file should have an entry like this: "main": "index.js" “Index.js” is where all logic for your main program would be located. You can create additional “.js”, “.html” and “.css” files according to your needs. For the purpose of “HelloWorld” program explained in this guide, the command below will create three required files: $ touch index.js index.html index.css

 Install Electron

You can install Electron in your project directory by running the command below: $ npm install electron --save-dev Wait for the installation to finish. Electron will be now added to your project as a dependency and you should see a “node_modules” folder in your project directory. Installing Electron as a per-project dependency is the recommended way of installing Electron according to the official Electron documentation. However, if you want to install Electron globally on your system, you can use the command mentioned below: $ npm install electron -g Add the following line to “scripts” section in “package.json” file to finish Electron setup: "start": "electron ."

 Create Main Application

Open “index.js” file in text editor of your choice and add the following code to it: const { app, BrowserWindow } = require('electron');function createWindow () { const window = new BrowserWindow({ width: 1600, height: 900, webPreferences: { nodeIntegration: true } }); window.loadFile('index.html');} app.whenReady().then(createWindow); Open “index.html” file in your favorite text editor, and put the following code in it: <!DOCTYPE html><html><head><link rel="stylesheet" href="index.css"></head><body><p id=”hworld”>Hello World !!</p></body></html> The javascript code is pretty self explanatory. The first line imports necessary Electron modules needed for the app to work. Next, you create a new window of the standalone browser that comes with Electron and load the “index.html” file in it. The markup in the “index.html” file creates a new paragraph “Hello World !!” wrapped up in the “<p>” tag. It also includes a reference link to the “index.css” stylesheet file used later in the article.

 Run Your Electron Application

Run the command below to launch your Electron app: $ npm start If you have followed instructions correctly so far, you should get a new window similar to this: Open “index.css” file and add the code below to change the color of “Hello World !!” string. #hworld { color: red;} Run the following command again to see CSS style applied to “Hello World !!” string. $ npm start You now have the bare minimum set of required files to run a basic Electron application. You have “index.js” to write program logic, “index.html” for adding HTML markup and “index.css” for styling various elements. You also have a “package.json” file and “node_modules” folder containing required dependencies and modules.

 Package Electron Application

You can use Electron Forge to package your application, as recommended by the official Electron documentation. Run the command below to add Electron Forge to your project: $ npx @electron-forge/cli@latest import You should see some output like this: Checking your system Initializing Git Repository Writing modified package.json file Installing dependencies Writing modified package.json file Fixing .gitignore We have ATTEMPTED to convert your app to be in a format that electron-forge understands. Thanks for using "electron-forge"!!! Review “package.json” file and edit or remove entries from “makers” sections according to your needs. For instance, if you don’t want to build an “RPM” file, remove entry related to building of “RPM” packages. Run the following command to build the application package: $ npm run make You should get some output similar to this: > helloworld@1.0.0 make /home/nit/HelloWorld> electron-forge make Checking your system Resolving Forge Config We need to package your application before we can make it Preparing to Package Application for arch: x64 Preparing native dependencies Packaging Application Making for the following targets: deb Making for target: deb - On platform: linux - For arch: x64 I edited the “package.json” file to build only the “DEB” package. You can find built packages in the “out” folder located inside your project directory.

 Conclusion

Electron is great for creating cross-platform applications based on a single codebase with minor OS specific changes. It does have some issues of its own, most important of them is resource consumption. Since everything is rendered in a standalone browser and a new browser window is launched with every Electron app, these applications can be resource intensive compared to other applications using native OS specific application development toolkits.

Vue.js Template Introduction

Vue.js, which is used to build user interfaces (UIs) and single-page applications (SPAs), combines many of the best features of the JavaScript frameworks Angular and React, and many developers like to use Vue.js because it provides a neutral environment. Like HTML, Vue.js has a template syntax, and we can use template syntax to bind the DOM with the components data. In this article, we will show you how to insert data into the template syntax and the ways to interpolate different types of data.

 Text Interpolation

If we want to bind a variable from the relative component instance, we can use double curly braces, which is also referred to as “mustache” syntax. <p> {{ linuxhintText }} </p> Vue.js offers two-way binding, which means that, whenever the value of a variable is changed, the element will be rendered again. However, if we do not want it to be updated, we can use the v-once directive. <p v-once> {{ linuxhintText }} </p>

 Raw HTML Interpolation

Vue.js does not allow for the data binding of plain text, but we can bind raw HTML text using the v-html directive. In the example below, we have a variable in a component called rawHTML that contains some raw HTML text. data() { return { msg: "Hello Vue", rawHTML: "<p> Linuxhint is <b>Great</b> </p>" }} We can bind the rawHTML variable using v-html directive as follows. <template> <h1>{{ msg }}</h1> <div v-html="rawHTML"></div></template> The div tag will have a p tag inside it.

 Attributes Interpolation

In the raw HTML interpolation, we did not use double curly braces to bind the variable. Therefore, if we want to bind a variable inside the HTML attribute, we can use the v-bind directive. <div v-bind:class="container"></div>

 Expressions

Vue.js does not only provide features for binding a variable. Vue.js can be used to write various types of expressions within double curly braces. {{ count + 1 }}{{ check ? "true" : "False" }}{{ arr.sort().reverse() }}

 Wrapping Up

In this article, we introduced Vue.js’s simple yet useful template syntax. However, there is a lot more to learn about Vue.js. You can visit the official website of Vue.js here, and you can keep learning about JavaScript with linuxhint.com.

Install Vue.js in Ubuntu 20.04

In this tutorial, we will provide an easy step-by-step process to help you get started with Vue.js. Vue.js is a powerful, progressive, reactive JavaScript framework that is approachable and easy to learn. It provides many different tools and libraries that facilitate the application development process. If you have knowledge of HTML, CSS, and JavaScript, you can start building web applications with Vue.js in no time.

 Installation

To integrate Vue.js into a project, you can use the CDN package, NPM, or CLI.

 Using the CDN Package

If you want to start learning Vue.js, then it is best to use the CDN package. You can simply add the following script tag in your project to get started. <script src="https://unpkg.com/vue@next"></script></td> However, this method is not recommended for production purposes because it can lead to issues with compatibility in the future.

 Using NPM

For large-scale production applications, you should install Vue.js using NPM. To use this method, you must have Node.js installed on your machine. If you have not installed Node.js yet, you can find out how by reading our article How to Install Node.js and npm on Ubuntu 20.04 – Linux Hint. If you have already installed Node.js, then you can install Vue.js by running the following NPM command in your terminal # latest stable $ npm install vue@next

 Using CLI

Vue CLI is a complete package for Vue.js development. CLI is installed globally using the NPM package manager. Before installing Vue.js using the Vue CLI method, you must have some prior knowledge of Node.js and front-end build tools. In addition, we can use either npm or the yarn package manager. $ sudo yarn global add @vue/cli# OR $ sudo npm install -g @vue/cli After installing the latest version of Vue.js using Vue CLI, you can easily upgrade your projects. To check your version of Vue.js, you can run the following command vue --version If you want to upgrade to the latest stable version of Vue.js, you can use the following Vue CLI command. $ sudo yarn global upgrade --latest @vue/cli# OR $ sudo npm update -g @vue/cli

 Getting started with Vue.js

To get started with Vue.js, to create a project using Vue CLI using the following command. vue create demo-app After running this command, you will be asked to choose a preset. You can either go with the default or add custom features. You can also use the GUI method to create a Vue project by using the following command. vue ui This command will open a window in the browser to help you create a project.

 Summary

In this article, we showed you how to install Vue.js using three different methods. After installing Vue.js, you can efficiently manage your web application. If you want to start using Vue.js right away, you can use the CDN package method. However, for production purposes, you should use either the NPM method or the CLI method. To learn more about Vue.js, you can visit the official website here: Vue.js.

Javascript Form Validation

Form validation is the basic and most important part of the web development process. Usually, form validation is done on the server-side. Form validation helps in showing error messages to the user if there is any unnecessary or wrong data is provided, or a required field is left empty. If the server finds any error, it throws back that error; then, we show the error message to the user. But, we can use javascript at the front-end to validate the form data and show errors right away. In this article, we will learn the basic form validation. So, let’s get straight to the examples and see how can we do that.

 Examples

First of all, we assume a form with the name of “testForm,” in which we have an input field with the label “User Name,” and an input type submits in our HTML file. In the form tag, we have created an onsubmit event, in which we are making closure and returning a function validateFunc(). <form action="" method="get" name="testForm" onsubmit="return(validationFunc())"> <label for="name">User Name</label> <input type="text" name="name"><br> <input type="submit" value="Submit"></form> In the script file, we will write the function definition of validateFunc(), which will get executed every time when the user hits the submit button. In that function, we will validate the username input field. We suppose that we want to validate either the username field is empty or not when the user hits the submit button. So, to validate the username field. We first assign a variable to the document.testForm, just to give a clean and understandable look to the code. Then, in the function definition, we will write the code for validation. We will write an if statement to check the empty form field. If the username field is empty, we will show an alert box to show the error, focus on the username field again, and return false so that the form won’t get submitted. Otherwise, if it passes the check and data get validated, we will return true to the function. var theForm = document.testForm;// Form validation codefunction validationFunc() {if (theForm.name.value == "") { alert( "name is empty" ); theForm.name.focus(); return false;}return (true);} After writing all this code. If we run the code and click on the submit button without writing anything in the form field. As you can observe in the screenshot attached below, it throws an error in the alert box. This is a very basic yet good example to get started with implementing the form validation. For further implementation, like multiple form validations or you want to have a check on character length as well. For that purpose, we first suppose two form fields in the form tag with the label of “email” and “password” in our HTML file. <form action="" method="get" name="testForm" onsubmit="return(validationFunc())"> <label for="name">User Name</label> <input type="text" name="name"><br> <label for="email">Email</label> <input type="email" name="email" id="><br> <label for="password">Password</label> <input type="password" name="password" id="><br><br> <input type="submit" value="Submit"></form> For validation, we will again put an if statement for validation of the email and password form fields in the function definition of the script file. Suppose we want to apply multiple validations on the email field like the field should not be empty, and its length should not be less than 10 characters. So, we can use OR “||” in the if statement. If any of these errors occur, it will show an alert box with the error message that we want to show, focus on the email form field, and return false to the function. Similarly, if we want to apply the character length check on the password field, we can do so. var theForm = document.testForm;// Form validation codefunction validationFunc() {if (theForm.name.value == "") { alert( "name is empty" ); theForm.name.focus(); return false;}if (theForm.email.value == "" || theForm.email.value.length < 10) { alert( "Email is inappropriate" ); theForm.email.focus(); return false;}if (theForm.password.value.length < 6) { alert( "Password must be 6 characters long" ); theForm.password.focus(); return false;}return (true);} After writing all this code, reload the page to have updated code. Now, either we leave an empty email field or write an email less than 10 characters. In both cases, it will show an “Email is inappropriate” error. So, this is how we can apply basic form validation. We can also apply data validation on the client-side using Regex or by writing our own custom function. Suppose we want to apply data validation on the email field. The regex would be like this for validating an email. if (/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(theForm.email.value)) { alert( "Email is inappropriate" ); theForm.email.focus() ; return false;} This was just a basic demonstration of data validation using regex. But, the sky is open for you to fly.

 Conclusion

This article covers the basic form validation. We have also tried and have a sneak into the data validation using regex. If you want to learn more about regex, we have a dedicated article related to regex on linuxhint.com. For learning and understanding javascript’s concepts and more useful content like this, keep visiting linuxhint.com. Thank you!

Javascript Try Catch

Javascript is a translative programming language. Just like any other language, a developer or programmer often needs to care about error handling. Mostly a programmer or developer needs to handle errors while accessing or assigning some data to the database. So, error handling is an essential part of any programming project. There are three types of errors in programming that a programmer or developer often has to face. Syntax Error– An error in writing code against the syntax of programming language. For example, missing a semi-colon or not following the convention of creating and calling the function. Logical Error– An error in the logic building. For example, implementing the wrong arithmetic operation, which results in the wrong output. Runtime Error– Error occurred during the runtime. Like, calling a function without declaring it. The error that we get during the runtime is also known as anexception. Exceptional handling is very important. Because we can’t throw the errors and error codes right away. We have to handle that. So, In this article, we are going to have an understanding of how to handle exceptions using javascript’s try-catch block. We will also learn how to throw a custom message against an error and how to use the “finally” block with a try-catch block.

 Syntax

The syntax for using a try-catch block is very simple and easy to use. We can simply use the try-catch block like this try { //code to try or test throw //throw a custom error to catch} catch (error) { // code after getting an error } finally { // code which executes in any case} In this syntax, we first write some lines of code in the “try” block to test. If that code gets executed or passed the test successfully. The “try” block won’t throw any error to the “catch” block and execute the “finally” block. Otherwise, it will throw an error to the “catch” block where we can handle the exceptions according to the given error. We can throw a custom error to the “catch” block as well using the “throw” keyword. “Finally” block will get executed in any case. Either the “try” block throws any or not. Let’s try a couple of examples to have a better understanding.

 Examples

First of all, to demonstrate the simple and basic working of the try-catch block. We try to call a function without declaring it anywhere. addition() It will definitely throw an error in the console But, if we try to call it in a try block now try { addition()} catch (error) {} It won’t show any error in the console anymore because we did not write any code in the catch block for error. So, we can modify and console the error message in the catch block now. try { addition()} catch (error) { console.log("Error Message => " + error)} We can see our custom message in the console against the error. So, this is the very basic usage of the try-catch block. Now, let’s learn about throwing a custom error in the try block.

 Throw

Suppose we want to throw a different custom error on the base of different errors while trying. We can throw a custom error, that “Function definition doesn’t exist.” Like this try { throw new Error ("Function definition doesn't exist")} catch (err) { console.log("Error Message => " + err)} As you can see in the output, the error message is now changed to our custom error thrown.

 ProTip

Suppose we try to apply this try-catch on an asynchronous function. It won’t work. Because the engine would have moved to the next line, execute the final block, and the asynchronous function would get executed later. For example, if we apply the setTimeout Function inside a try-catch block. try { setTimeout(() => { addition(); }, 3000)} catch (err) { console.log("Error Message => " + err)} finally{ console.log("reached 'finally' block")} You can observe that the “finally” block gets executed first, and the error is thrown later if we take a look at the error. It is not the error from the catch block, but it is an original programming error, which means that the catch block doesn’t get executed because they try block didn’t find any error. Alright! Now, if we want to make it work. We have to apply the try-catch block inside the setTimeout function instead of outside. So, the true way of implementing an asynchronous function with a try-catch block would be like this. setTimeout(() => { try { addition(); } catch (err) { console.log("Error Message => " + err) } finally{ console.log("reached 'finally' block") }}, 3000) You can observe in the output that after the delay of 3 seconds because of the setTimeout function. We have got the error message from the catch block first, and then the “finally” block gets executed.

 Conclusion

In this article, We have learned to implement the try-catch block step by step in such an easy and profound way that any beginner after reading this article would be able to apply it anywhere he needs. So, keep on learning and getting experience with linuxhint.com. Thank you!

Javascript Random Number

While developing a gaming website, we often need to generate random numbers. In this article, we are going to know how we can get a random using the random method. The random method helps in generating pseudo-random numbers, since, arithmetically, generating a true random number is impossible.

 Syntax

We can get random numbers using Math.random() function, like this: Math.random(); This function doesn’t take any arguments and will return the random float number between 0 and 1. If we want to generate random numbers between any two numbers or up to a limit. The syntax would be different for them. For better understanding, let’s try a couple of examples.

 Examples

Suppose, we want to generate a random number from 0 to 99. The syntax for providing a limit or a range is: Math.random() * 100 Keep in mind that 100 is a limit or range, not the number. You can see that it has generated a number from 0 to 99, but, it’s a float number. So, if we want to have a whole number and not a float number, ,we can apply a Math.floor() method over Math.random() method, like this: Math.floor(Math.random() * 100) That looks great! Now, what if we do not want to have numbers from 0 to 99 or onwards but from some other number, for example, 50 to 90. First, let’s see how we can do that, and later we will see how it works. Math.floor((Math.random() * 40) + 50) In this syntax, 40 is the range or limit from 50 to onwards, 50 as the starting number. In the end, if we want to build our custom random function to which we can provide two numbers (minimum and maximum) and get a random number between those two numbers. The function would be like this: function getRandomNum(sNum, lNum) { return Math.floor((Math.random * (lNum - sNum)) + sNum)} Keep in mind that the ending number or “lNum” will be excluded. In case you want to include that as well add “1” in the range, like this: function getRandomNum(sNum, lNum) { return Math.floor((Math.random * (lNum - sNum + 1 )) + sNum)} After writing this function. Let’s call it and see the results. getRandomNumber(20, 40); As you can see, we are getting random numbers from 20 to 40. So, these are some of the different ways to generate pseudo-random numbers using the Math.random() method.

 Conclusion

In this article, we have learned to get random numbers and tried several techniques to get the desired results. We have also learned to make a custom function in which we can provide the range of numbers and get the random numbers between that ranges. So, keep on learning Javascript with linuxhint.com to have a better grasp over it. Thank you!

JavaScript onClick

 Introduction

JavaScript is a well-known programming language. It is used in more than 95% of the websites we interact with daily. You may often see that on the click of a button, a whole page gets changed, a form field is opened, or a pop-up box appears. From the perspective of a programmer/developer, how can we implement such functionality and handle the website’s interactions with users? When it comes to interaction, JavaScript provides built-in functions to control events on a site. There are two types of events: Event Listener – listens and waits for the event to get fired Event Handler – executed when an event is getting fired In this article, you will learn about the most used event handler of JavaScript, the onClick event. There are other event handlers for hovering over an element or for keyboard key presses, but in this article, we will focus on the onClick event. The onClick event is used to perform certain tasks at the click of a button or by interacting with an HTML element. We will now show you an example to demonstrate how the onClick event works.

Example: Change Text Using onClick

In this example, we will change a selection of text on the click of a button using the onClick event. First, we will make a paragraph tag and give it an ID “paragraph” to access it later. We will create a button with the onClick event and call the function named “change.” <p id="paragraph">Linuxhint</p><button onclick="change()">Change!</button> In the script file, we will create a flag variable that will allow us to check the status of the text in our HTML paragraph tag. Then, we will write a function defining the “change” function. In the function definition, we will create an “if” statement, in which we will check the status using the flag variable. We will also change the text and alter the flag. It is a pretty simple piece of code! var a = 1; function change(){ if (a==1) { document.getElementById("paragraph").innerHTML = "Linuxhint is awesome" a = 0; } else { document.getElementById("paragraph").innerHTML = "Linuxhint" a = 1; }} All right! After writing all this code, we will run the code, move to our browser, and click the newly created button. After clicking the button, the text should be changed from “Linuxhint” to “Linuxhint is awesome.” We can apply the same technique anywhere to change the content of our website according to our needs. We can use it in changing an image or performing any type of task that we can imagine with this tool.

 Conclusion

This article explains how to use the onClick event. In this article, you learned the concept of the onClick function in a practical way. The usage of the onClick event is so simple, even a beginner can start working with this function. You may continue learning, working, and gaining more experience at linuxhint.com to have a better grasp of this programming language. Thank you so much!

JavaScript Cookie

JavaScript is the language behind almost every website you will use. JavaScript is the language of the online world and is used in online communication, as well. The concept and need for cookies arose when developers wanted to store user information in the browser to avoid overloaded communication over a stateless HTTP server. A cookie is like a file containing some data that is stored on the user’s machine. The information stays on the computer, even if the user closes the website or closes the browser. This article provides an overview of the use of cookies.

 Syntax

The syntax for creating and saving cookie is as follows: document.cookie = "cookieName=cookieValue" The cookie saves the data in key-value pairs.

 Creating a Cookie

You can create a cookie by assigning a string to the document.cookie, for example, userName. document.cookie="userName=John"

 Getting a Cookie

Now, if we want to have a look at the Cookie, we can get the cookie by assigning document.cookie to a variable and then console it. var cookieStat = document.cookie; console.log(cookie.Stat);

 Setting/Updating a Cookie

We can update a cookie as well using the same syntax we used for creating a cookie. To add the expiry date in the cookie, for example, we will use the following technique: var expiryDate = new Date(); expiryDate.setDate(expiryDate.getDate() + 1) expiryDate.toUTCString() document.cookie = "userName=John" document.cookie = "expires=" + expiryDate.toUTCString() After updating, take a look at the cookie: console.log(document.cookie) You can see that cookie is updated.

 Deleting a Cookie

There is no built-in method or object for deleting a cookie in Python, but a cookie is deleted when it expires. By assigning a past date to a cookie, you can delete it. var expiryDate = new Date(); expiryDate.setDate(expiryDate.getDate() - 1) expiryDate.toUTCString() document.cookie = "userName=John" document.cookie = "expires=" + expiryDate.toUTCString() After assigning a past date, the cookie will no longer work and will self-delete by expiring.

 Conclusion

So, this is how you can create a cookie, set or update a cookie, and delete a cookie. In this article, you learned about cookie usage, including how cookies can help you in development and save necessary user data. You can continue to learn more about JavaScript at linuxhint.com. Thank you!

Javascript Refresh Page

Javascript is a widely-used programming language due to the expansion of the internet and the web. In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life. Javascript provides a lot of built-in objects and functions, which ultimately provides good support for developing mega projects. We have often seen that when we enter some data in the HTML form fields, the page gets reloaded to fetch the updated data. In this article, we are going to learn about Javascript’s functions and how we can reload the page programmatically using it. There are actually around 535 ways to reload a page. Yes, 535 ways. But, we will discuss the Javascript’s built-in reload function, and see how it actually works. So, let’s get started! Javascript’s built-in reload function is used to reload/refresh the current web page or specific area.

 Syntax

The syntax for the reload function is: location.reload(); This function doesn’t return any parameters. But we can pass true or false. In the case of true, the web page must have to be reloaded from the webserver. Otherwise, for false, the web page is supposed to be reloaded from the cache of the web browser. Let’s take a look at the examples and learn in a better way.

 Examples

First, if we simply call the function. It will definitely reload the page. location.reload() And if we pass true, it will reload the page from the webserver. location.reload(true); And if we pass false, it will reload the web page from the browser’s cache. location.reload(false); We can also reload the page using a function and the onclick event of a button. First, create a button with the onclick event in the HTML file. <button>Reload!</button> And in the script file, the function should be like this. function reloadPage(){ location.reload();} So, this is a piece of very basic and still very profound knowledge about Javascript’s reloaded function.

 Conclusion

In this article, we have learned about Javascript’s built-in reload function for reloading/refreshing the web page. This video contains a detailed yet very simple and easy to understand the concept of Javascript’s built-in reload function. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much.

Javascript Get URL

Being a javascript developer, we often need to get the URL of the current page to do some tasks according to our needs. In this article, we are going to learn how we can get the current URL, know what its syntax is, and how we can extract different parts using the built-in window.location object. The simplest and most straight forward way of getting the URL of the current page is shown below: window.location.href But, if we take a sneak peek into the window.location in the developer’s console, it is shown below: We can observe what it has for us. We could receive a good amount of information from the Window.location object. For example:

 Examples

If we want to get the protocol only, like HTTP or HTTPS, from the whole URL, we can get that using the very simple window.location.protocol, like the picture below: window.location.protocol And if we want to get the hostname from the URL, we can simply get that using the window.loation.host. window.location.host And similarly, if we want to get the pathname only, we can get that using window.location.pathname. window.location.pathname For getting the search query, we can use window.location.search. window.location.search So, these are basically some of the ways to get the current URL and extract some specific parts from it according to our requirements. Moreover, window.location has a lot of other options for us.

 Conclusion

In this article, we have learned about the window.location object, how we can use it to get the current URL, and extract some specific parts from that. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much.

Javascript Print Page

Javascript is a scripting or programming language, which is most commonly used nowadays in the web industry. It provides a lot of built-in objects, functions, and methods to perform several tasks. In this article, we are going to have a look at one of them which is used to print the web page. So, let us get started! You must have encountered some websites that provide a button to print the whole web page, or you must have felt the need to print a web page but there is no print button there. Javascript’s built-in object window provides us a method named print(). We can use window.print() function to fulfill this requirement.

 Syntax

The syntax of the print function is: window.print(); This simple syntax neither gets any parameters nor returns anything. It simply fires the print window. We simply have to make a button in our HTML, and on the on-click event of that button we can directly call the window.print() function. <button onclick="window.print()">Print</button> Then, on the web page, if we click the button, it will open up a window or dialog box, which we usually see while printing any document. Be careful that it will print everything on the webpage. Either that web page includes images or advertisements.

 Conclusion

In this article, we have learned how we can print the whole web page, and the benefits and consequences of doing that. This article explains the need and the usage of javascript’s built-in window.print() function. So, keep on learning javascript’s concepts with linuxhint.com.

Javascript Alert

Javascript is the most known language of the web. Javascript is widely used in front-end development as well as in the back-end. Javascript provides a lot of built-in functions to help in development. In this article, we are going to learn one of the javascript’s built-in alert() method, which is used to show pop-ups over the screen to either display a message or show a warning. The alert box is different from any other message or text on the screen. It is a pop-up that contains a message/text with an “OK” button. The user won’t be able to do any task while an alert box is over the screen, and he/she clicks the “OK” button. So, it is not recommended, if not needed. So, let’s have a look at what is an alert box and what are the different ways to use it. The alert() is basically a method, which is used to show a pop-up box over the web page.

 Syntax

There are two different syntaxes for showing the alert box. One of them is using the window’s object. window.alert("Alert box from the linuxhint"); But, we can use the alert() method without the window’s object as well. alert("Alert box from the linuxhint"); So, let’s try both of the syntaxes.

Examples

First, let’s try with the window’s object. window.alert("Alert box from the linuxhint"); And now, without the window’s object. alert("Alert box from the linuxhint"); You will witness that there is no difference in both of them. The alert method doesn’t only take the string to show the message. We can provide variable as well, and it worked perfectly fine, var alertMessage = 'Alert Box using variable'; alert(alertMessage); as you can see in the screenshot below that the message is displayed. We have learned about providing a variable as well. What if we want to show the pop-up alert box on the screen at the click of a button? For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that says “Added successfully”. So, we can simply show an alert box like this. <button onclick="alert(Added successfully)">Show Alert!</button> Or, if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got. We can call the function on the button’s onclick method <button onclick="alertFunc()">Show Alert!</button> Then, later in the script, we can write the function in which we can show the alert message. function alertFunc() { var alertMessage = 'Alert Box using function'; alert(alertMessage);} So, these are some of the different methods of using the alert() method.

 Conclusion

In this article, we have learned about the javascript’s built-in alert method to show pop-up over the browser’s window. This article has explained the use of the alert method in a very easy, profound, and effective way that any beginner can understand and use. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much!

Javascript Map

In this article, we are going to learn one of the most widely used methods for the array, which is the map() method. The map method helps in mapping arrays according to our requirements. Let’s see, what is a map() method? What is the syntax for mapping arrays using the map() method? The array’s map method is used to construct a new mapped array based on the return value of the callback function for each element. var mappedArray = array.map(callbackFunction, thisValue) The callback is the function that will be called every time for a single element and return a value that will be stored in a new array. The syntax for the callback function is function(value, [index[, array]]) value is a necessary argument, which is actually a single element of the array. The index is an optional argument that will be used as the index of each element in the callback function. The array is an optional argument as well. We can pass this argument if we want to use the array in the callback function. thisValue is the value we want to pass, which will be used as a “this” in the callback function. Otherwise, “undefined” will be passed. Javascript provides the for…in loop and foreach loop for iterating through elements and manipulating arrays. But, why do we need a map method aside from that? There are two major reasons for that. One is the separation of concern and the second is the easy syntax for doing such tasks. So, let’s try some different examples to demonstrate the purpose and right use of it.

 Examples

First of all, we are going to have a simple demonstration in which we have a simple array of numbers on which we will try to perform any simple arithmetic operation over every single element. var arr = [4, 8, 16, 64, 49]; Now, before applying the map method over this array. We will first write a callback function to which we can call in our map function in which, let’s say we want to multiply each element with 10 and have a new array. function multiply(element){ var newElement = element * 10; return newElement;} Everything is set up to apply the map method over the array and have the results required. var newArr = arr.map(multiply); Now, if we have a look at the “newArr”, console.log(newArr); We can see the latest mapped array in the output as per our requirement. Keep this in mind that the length of the new mapped array will definitely be equal to the original array. There is a shorter way of doing the same task using the arrow or anonymous function within a map method. So, we can write a callback function within a map method like this var newArr = arr.map((element) => { return element * 10}) Or, if we want to be a pro and make it more concise. We can do this var newArr = arr.map(e => e * 10) Alright! So, this was the very basic demonstration of the map method and different ways to write the call back function. But, this function comes more in handy, when we are playing with an array of objects. That’s where it’s true implementation happens.

 Using Map with an Array of objects

In this example, we suppose an array of objects in which each object contains the information of a player. Player’s name and his ID. var arr = [ { id: 12, name: "James"}, { id: 36, name: "Morgan"}, { id: 66, name: "Jordan"}]; Now, let’s say we want to extract the IDs from each object and have a new array of IDs. But, in order to understand, how the map method is different and helps better than the foreach loop. We will try both of these(map method and foreach loop) to do the same task and learn the difference. So, first, we will try to extract IDs using the foreach loop and then using the map method. var extractedIDs = []; arr.forEach((element) => { return extractedIDs.push(element.id);}) Now, if we have a look at the extracted IDs. console.log(extractedIDs); We have got them separated in an array. But, now let’s demonstrate the same output using the map method. var extractedIDs = arr.map((element) => { return element.id;}) console.log(extractedIDs); By looking at the difference in code and the same output, we can realize the true difference between the two(foreach and map) methods. The syntax and separation of concern. Similarly, we can perform a lot of other operations. If we have to play and get some data from the array of objects. We suppose an array of objects in which each object contains two properties: first name and last name. var arr = [ { firstName: "John", lastName: "Doe"}, { firstName: "Morgan", lastName: "Freeman"}, { firstName: "Jordan", lastName: "Peterson"}]; Now, we want to have an array that contains the full names. So, we will write a map function like this to fulfill our purpose var fullName = arr.map((person) => { return person.firstName + ' ' + person.lastName}) console.log(fullName); As you can see, we have got a separate array with full names. That’s great. So, these are some of the basic and different ways of how a map function can be used to fulfill our development requirements and helps in every javascript developer’s life.

 Conclusion

In this article, we have learned about javascript’s most used map() method for arrays and we have learned some of the different ways to use the map method. This article explains the concept of the map method in such an easy and profound way that any beginner coder can understand it and utilize it to his needs. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much!

Javascript Sort

As we have to manage arrays in almost all programming languages, JavaScript is no different. Arrays are usually used to store data like strings, numbers, objects, and undefined. With the exponential growth of online data, we frequently need to manage and sort the data. Sorting is kind of a massive experience in almost every programming language. It takes a lot of effort, machine power, and calculations to do the right sorting. With the expansion of data, we need to sort and structure the data in a beautiful way. Javascript provides a built-in array mutator method sort() for sorting arrays. In this article, we will have a look at Javascript’s built-in sort() method and learn what the Javascript sort method is, as well as how we can use it for our purpose to sort elements in an array. Let’s go ahead and start working! The sort method is used to arrange different elements in an array in a specific order.

 Syntax

The general syntax for the sort method is: array.sort(); This method returns the sorted array in ascending order by default. We would discuss a couple of examples to understand the sort method.

 Examples

We suppose an array of string in which we have some different names of Linux operating systems. let arr = ["Ubuntu", "Fedora", "CentOS", "Debian", "Kali Linux"] Now, if we apply the sort method over this array: arr.sort(); It will definitely sort the array in alphabetical order. We can see the output in the screenshot below. But, if we want to get the string in reverse/descending order. We can apply a Javascript’s built-in reverse function over the sorted array like this: var sortedArray = arr.sort(); sortedArray.reverse(); The shorter way to do the reverse is: arr.sort().reverse(); Alright! It worked fine for the string. Let’s try if it works for the numbers as well. So, we first suppose an array of numbers. let arr = [14,8,33,27,6] Then apply the sort method over the array of numbers. arr.sort(); It seems like it didn’t work well as it did for the string. Because the sort method first converts the numbers into the strings and then sorts on the base of Unicode. Although, “8” comes before “14” in numerical order. But, in UTF-16 code units order, “14” comes before “8”. The good thing, we got the solution for this.

 CompareFunction

Here comes the concept of compare function that comes in handy in helping sort the numbers. We can use a compare function to the sort method as a callback function, which takes two elements. It then sorts them according to our requirement in the compare function and returns them to the sort method, continuously doing this until it reaches the end of the array. The syntax for the sort method with the compareFunction would be like this: array.sort(compareFunction); Now, if we take a look at the technical details of the compareFunction, that is how it actually works. If we do not provide a compareFunction to the sort method, it will sort according to the UTF-16 code unit orders. If we utilize the compareFunction, all elements would be sorted in accordance with the return value of compareFunction. So, if we want to write a compare function for the numbers. That would be just like this: function (a, b) { return a - b } CompareFunction takes two values at a time and returns three types of values. True or “1”, if the first value comes before the second value or the first value is greater than the second value: False or “-1”, if the first value comes after the second value or the first value is greater than the second value. And “0”, if two values are equal. Now, if we try to apply it to sort the array of numbers. We can apply it like this: arr.sort(function (a ,b){ return a - b }) As you can see in the output, array having numbers have been sorted decently. The shorter way of doing the same task will be like this: arr.sort((a, b) => a - b) But, this works only for the comparison of the numbers. We can also use the sort method to sort the array of objects depending on the values of the object, which we want to sort the array of objects. If suppose we would want to sort on the base of the number of users an array of objects in which every object includes the Linux Operating Systems and the number of their users, then we will be using the following: arr = [ {name:"Ubuntu", users:3000} {name:"Fedora", users:1500} {name:"CentOS", users:2000} {name:"Debian", users:5000} {name:"Kali Linux", users:4000}] So, in order to sort on the base of users. The sort function would be like this: arr.sort(() => { return a.users - b.users }) So, these are the different ways of using the sort method to sort the arrays of any type.

 Conclusion

In this article, we have learned how we can sort an array of different types using Javascript’s built-in sort function. This article explains the concept of the sort function from novice to intermediate level in a very easy, profound, and effective way. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much.

Applying JavaScript’s setTimeout Method

With the evolution of the internet, JavaScript has grown in popularity as a programming language due to its many useful methods. For example, many websites use JavaScript’s built-in setTimeout method to delay tasks. The setTimeout method has many use cases, and it can be used for animations, notifications, and functional execution delays.Because JavaScript is a single-threaded, translative language, we can perform only one task at a time. However, by using call stacks, we can delay the execution of code using the setTimeout method. In this article, we are going to introduce the setTimeout method and discuss how we can use it to improve our code. The setTimeout method is a built-in method that takes a callback function as an argument and executes it after a given amount of time. The syntax for the setTimeout method is as follows: setTimeout(callbackFunction, delay, arguments...) The callbackFunction is the function we want to execute after a given amount of time; the delay is the time in milliseconds after which we want to execute the callback function; and the arguments are other parameters we want to pass to the callback function. Now, we will apply the setTimeout method. First, we define a function called linuxhintFunc that prints the string “Hello from Linuxhint.” function linuxhintFunc() { console.log("Hello from Linuxhint.");} Next, we call linuxhintFunc in setTimeout and provide a time delay of 2000 ms (2 s). setTimeout(linuxhintFunc, 2000) Once the web page is loaded, there is a delay of 2 s before the function is called. We can perform the same task using the arrow function or an anonymous function. setTimeout(() => { console.log("Hello from the Linuxhint");}, 2000) Again, there is a delay of 2 s. Note: The setTimeout method is an asynchronous method, which means that, although JavaScript is a single-threaded language, this function runs on a different thread. The setTimeout method places the function in the queue of the call stack and waits until the call stack is free. If we try to print a message or run a function in setTimeout without a delay, then this action would be jump to the front of the queue first and run when the setTimeout method is executed. console.log("Hello from the Linuxhint-1") setTimeout(() => { console.log("Hello from the Linuxhint-2")}, 0) console.log("Hello from the Linuxhint-3") Looking at the output, the order of the output is not the same as that of the input. Therefore, the setTimeout function can delay the execution of code.

 Conclusion

This article introduces JavaScript’s built-in setTimeout method and discussed how we can use it. We hope that you learned something from this article and that you continue learning about JavaScript with linuxhint.com.

How to Get Current Date & Time?

Javascript has become a massively used programming language due to the expansion of the internet and the web at an unbelievable pace. In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life. We frequently used to see the date and time at almost every website. In this article, we are going to have a look at how we can get the current time and what are the different ways to get the date and time according to our requirement. Javascript provides a built-in object Date, which helps in managing all the date and time. Later, we can extract whatever we want according to our needs using different built-in methods. So, let’s just straight jump into the process and learn the different techniques to extract the current date and time. First of all, we will create a new object of Date() and declare a variable named “current” and assign the new Object of Date() to a “current” variable. var current = new Date(); After assigning, let’s have a look at the object Date what does it have for us. console.log(current) Alright! It looks pretty cool in a good format. But, how about if we want to get only the year from the entire date? We can use the built-in function getFullYear() for getting the year only. current.getFullYear(); Similarly, if we want to extract only the year, we can use the built-in function getMonths() for getting the month only. current.getMonth(); There seems like an issue. This is not the 8th month(August)! As we can see in the above complete output for the new Date object. This is September. Well, this is because of the digital(0-11). So, we have to add “1” to it for getting the right month every time. current.getMonth() + 1; This is fine now. Just like for the year, we can do the same for the date. For example, to extract or get only the date, we can use the built-in function getDate(). current.getDate(); Just like a date, we have built-in functions for extracting the desired piece of time. For example, if we want to get or extract the hours only, from the whole current time, we can use the built-in function getHours(). current.getHours(); The same goes for the minutes. To extract minutes only, we can use getMinutes(). current.getMinutes(); To extract seconds only, we can use getSeconds(). current.getSeconds();

 Advanced built-in functions

Here we have some advanced built-in functions to get the date and time in a pretty clean and good formatted string. For example, in order to get only the time, not the date, in the form of string we can use the built-in function toLocaleTimeString() to our purpose. current.toLocaleTimeString(); // "2:42:07 PM" And, if we want to extract only the time in the form of string. We can use the built-in function toLocaleDateString(). current.toLocaleDateString(); // "9/29/2020" And, if we want to extract both the date and time in a single string, we can use the built-in function toLocaleString(). current.toLocaleString(); // "9/29/2020, 2:42:07 PM" So, this is how we can get the date and time using the built-in date object and extract the required months, years, or minutes using different methods.

 Conclusion

This article explains how we can get the current date and time and how we can use it to our needs in a very easy, profound, and effective way that any beginner can understand and use. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much!

Javascript Confirm Method

Javascript is the most known language of the web. Javascript is widely used in front-end development as well as in the back-end. Javascript provides a lot of built-in objects, functions, and methods to help in web development. In this article, we are going to learn one of the javascript’s built-in confirm() method, which is used to show pop-ups over the screen and get the user’s response. The confirm box is a bit different if we try to compare it with the alert box. It is a pop-up that contains a message/text with two buttons, “OK” and “Cancel”. The user won’t be able to do any task while a confirm box is over the screen, and he/she clicks the “OK” or “Cancel” button. This is the reason behind not recommending it’s often used. So, let’s have a look at what is a confirm box and what are the different ways to use it. The confirm() is basically a method, which is used to show a pop-up box over the web page, and it contains a message or text and two buttons, “OK” & “Cancel”. On the click of the “OK” button, the confirm method returns “true”. Similarly, on the click of the “Cancel” button, it returns false.

 Syntax

There are two different syntaxes for showing the confirm box. One of them is using the window’s object window.confirm(message); But, we can use the confirm() method without the window’s object as well. confirm(message); In this syntax, the message can be any string or a variable that can include a message. So, let’s try both of the syntaxes.

 Examples

First, let’s try with the window’s object window.confirm("Confirm message from Linuxhint"); And now without window’s object confirm("Confirm message from Linuxhint"); You will witness that there is no difference in both of them. The confirm method doesn’t only take the string to show the message. We can provide variable as well, and it worked perfectly fine. var confirmMessage = Confirm Message using variable'; confirm(confirmMessage); As you can see in the screenshot below that the message is displayed. We have learned about providing a variable as well. What if we want to show the pop-up alert box on the screen at the click of a button. For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that “Confirmed”. So, we can simply show a confirmation box like this. <button>Show Confirm Box!</button> Or if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got. We can call the function on the button’s onClick method. <button>Show Confirm Box!</button> And later in the script, we can write the function in which we can show the confirmation message. function confirmFunc() { var confirmMessage = 'Confirm Box using function'; confirm(confirmMessage);} So, these are some of the different methods of using the confirm() method.

 Conclusion

In this article, we have learned about the javascript’s built-in confirm method to show pop-up over the browser’s window. This article has explained the use of the confirm method in a very easy, profound, and effective way that any beginner can understand it and use it. So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it. Thank you so much.

Applying JavaScript’s Splice Function

JavaScript is a lightweight programming language, and as with any programming language, when developing JavaScript programs, we often need to work with arrays to store data. In this article, we will introduce JavaScript’s built-in splice function and discuss how we can use it to manipulate an array. As data are generated, the structures used for storage must be updated. For this reason, a programmer must often add elements to or remove elements from an array. The splice function is used to add elements to or remove elements from an array at a given index, and it returns the elements removed from the array. The syntax for the splice function is as follows: array.splice(index, removeCount, items...) Here, index is the position at which we want to add or remove elements, removeCount, which is an optional argument, is the number of elements that we want to remove, and items, which is also optional, contains the elements we want to add. Now, we will go over a few examples to show how the splice function is implemented. First, suppose we have an array that consists of five elements. let arr = [10,20,30,40,50] To remove the elements 20 and 30 (at position 1 and position 2 in the array, respectively) from the array, we simply call the splice function and tell it to start from the first index and remove 2 elements. arr.splice(1,2); The values 20 and 30 are returned as the output. Next, we can look at the original array with the following command: console.log(arr); The two elements returned in the output are no longer in the array. Next, we will add elements to the array using the splice function. Because we will not remove elements from the array, we can provide a value of zero for removeCount and then provide the elements we want to add. arr.splice(2, 0, 30, 35); The above command returns an empty array because no elements were removed. However, if we look at the original array, we can see that it has been updated. console.log(arr); The values 30 and 35 were successfully added at the second index. Finally, if we want to remove elements and add elements, we can provide values for both removeCount and items. arr.splice(1, 2, 15, 20, 25); The above command has returned the two elements that were removed, and if we print the original array to the console, we can see that 20 and 30 are no longer in the array and that 15, 20 and 25 have been added. console.log(arr);

 Conclusion

In this article, we discussed several ways to use the splice function to update arrays. We hope you found this article useful and continue to learn JavaScript with linuxhint.com.

Javascript Trim String

Javascript is a scripting or programming language, which is used both on the client-side and back-end of the web. Just like any other language, strings are an important type of the variables, and we often need to manipulate or alter strings as per our needs. While getting data from the user in the form fields, a programmer has to take care of a lot of things. In this article, we will have a look at javascript’s trim() function. We will learn how this function helps in beautifying the strings and how can we get rid of extra spaces. So, let’s take a look at what is a string and how we can trim the strings. The string is a simple text or characters which can include the alphabets, numbers, or symbols. Javascript’s trim() method trims the extra white space from both sides of the strings. Extra white space can be space or tab, etc.

 Syntax

Syntax for the trim() method is as follows: string.trim(); In javascript’s trim string method, we simply call the function over a string, and it trims the string into a clean, space free string. This function doesn’t take any arguments. Let’s try some examples and understand it.

 Examples

First, we suppose a string and add some extra white space around the string. let str = " Linuxhint! " Now, to get rid of the extra white spaces from both sides, we try to apply the trim() method over that string and see how it works. str.trim(); We can see in the output that the string is trimmed and there is no extra whitespace left around the string as we desired it to happen. Now, a question arises: what if we want to trim the string from only the left side or the start of the string and vice versa. There is a built-in function for that as well. There are two different trimStart() and trimLeft() functions, but these both do the same task. So, if we want to trim the string from the left side only and want to keep the whitespaces on the right side. We can use the trimStart() or trimtrimLeft() function. str.trimStart(); str.trimLeft(); As you can see that both functions do the same task and trim the strings from the left side only. Similarly, if we want to trim the string from the last or the right side only. We can use any of the trimEnd() or trimRight() functions. str.trimEnd(); str.trimRight(); It is observed that the string is trimmed only from the right side, as we expected. So, this is how the javascript’s built-in functions trim(), trimStart(), trimLeft(), trimEnd() and trimRight() works and helps us in getting rid of the extra whitespace around the string.

 Conclusion

In this article, we have learned about javascript’s built-in string trim() function and see it’s various implementations. We have also learned about the trimStart() and trimEnd() functions. This article includes profound and explained in-depth knowledge, the need, and the usage of the javascript’s string trim function. So, keep on learning javascript with linuxhint.com.

JavaScript Sleep Function

Javascript is the language of freedom yet is a function-oriented language at the same time. Unlike other languages, javascript does not provide a built-in sleep() function. You can either build a custom sleep() function using the built-in setTimeout() function, or the latest ECMAScript promises an async-await function. This article shows you how to stop or pause the execution of the sleep function for a desired amount of time using promises or async-await functions.

 Before Starting

Before you start to build a sleep function, you need to understand that the setTimeout() function does not work if you expect it to stop the execution. Many programmers and developers try to use the function with loops but fail because the setTimeout() function is used to wait for some given amount of time and then runs the given function. You can, however, use the setTimeout() function to build a sleep function using promise if your purpose is to stop the execution for a desired amount of time.

 Using the Sleep Function

So, we will make a custom sleep function in which the function will get time in milliseconds as an argument and return a promise. The promise will include a setTimeout() function, which will pass the resolver as a function and time in milliseconds to the setTimeout() function. So, in the end, the sleep function should look like this: function sleep(ms){ return new Promise( resolver => setTimeout(resolver, ms));}; And now, wherever you want to use this sleep function, you can easily use it. Now, we will use this sleep function in a couple of examples to show you how to use it in practice. First, we will try to console some text and call the sleep function. Since the sleep function is returning a promise, we put a then function after it, in which we will console some text and pass the argument ‘5000’ to the sleep function. After running the program, you will see in the console that it will sleep for 5 seconds. console.log("Sleep function will wait for 10 seconds and then it will print 'Done'"); sleep(5000).then(()=>{ console.log("Done");}) You can witness the delay of 5 seconds to get to the “Done” status in the console. Suppose we want to perform an animation after every 2 seconds. To do so, we will simply write an asynchronous animation function, in which we will animate something, stop the execution for 2 seconds using sleep, and then repeat this process using a for loop for 10 times. async function animation(ms){ console.log("starting..."); for (let i = 0; i < 10; i++) { console.log("animation after 2 seconds...") await sleep(ms)} console.log("This is the end.");} After writing the asynchronous animation function, we can now call the animation function. animation(2000); After running the code, you will see in the console that the text “animation after 2 seconds” is repeating every two seconds.

 Conclusion

This article showed you how to make a custom sleep function, alongside multiple demonstrations. I hope this article has helped you to better understand the usage of sleep function. You can learn more about Javascript at linuxhint.com.

Javascript Redirect

Javascript is a web-oriented programming language. When using the web, you will often need to navigate through pages. When you click on any button, submit a form, or log in to any website, you get redirected to a different new page. Page redirection is an essential part of any website, but it is not only restricted to page navigation on a website. There can be multiple reasons to redirect the page, for example: The old domain name is changed to a new domain Submission and Authorization of a form On the base of the browser or language of the user Redirect from HTTP to HTTPS This article explains a few different ways to redirect a page.

 Syntax

The syntax for navigating to a page using javascript is as follows: window.location.href = "url" In this method, you simply provide the URL to which you want to redirect the user. The syntax for another method of redirecting a user to a new URL is as follows: window.location.replace("url") // or window.location.assign("url") In this functional syntax, you provide the URL to which you want to redirect, and whenever this function is called, you will be redirected to that specific URL. Here, “replace” and “assign” do the same task but with a subtle difference. They both redirect to a new URL, but “replace” does not take the record of history and the user cannot go back to the old URL or previous page. Meanwhile, “assign” keeps the history record and allows the user to go back to the previous page. We will now look at some examples of both syntaxes.

 Examples

First, we will create an on-click function on a button. <button onclick="redirectFunction()">Linuxhint</button> This function will redirect the user to the website “https://www.linuxhint.com.” function redirectFunction() { window.location.href = "https://www.linuxhint.com"} Now, if the user clicks on the button, they will be redirected to linuxhint.com In this next example, say, you want to redirect the user from an old domain to the new domain. For testing purposes, suppose the current address is the localhost, but whenever the user enters the URL of the localhost, the user gets redirected from the localhost to the new URL, which is linuxhint.com in this example. This is easier to do than you may think. To do this, simply use the syntax of the second redirect method: window.location.replace("https://www.linuxhint.com") Now, if the user enters the localhost URL, they will be redirected to linuxhint.com. But, if you look at the top-left button of the browser for going back to the previous page: the button is dulled and the browser is not allowing us to go back to the previous page. However, if you want to keep this option for the user, you can use “assign” instead of “replace.” window.location.assign("https://www.linuxhint.com") And now, if you look at the top-left button of the browser for going back to the previous page: The button is not dulled. You can go back to the previous page. It is recommended to use “replace” instead of “assign,” here, because the purpose of redirecting to a new URL is that the old URL is not working or not available anymore.

 Conclusion

This article explained a few different methods of redirection, along with real-life examples using these methods. In this article, you have learned how to navigate to a new page and how to redirect from the old URL to a new URL. You can learn more about javascript at linuxhint.com.

Joining Arrays

In JavaScript, as in many other scripting and programming languages, we often need to use arrays. Furthermore, it is often useful to combine the elements of an array into a single string. In PHP, for example, the implode function is used to join the elements of an array. In this context, “implode” can be viewed as a synonym for “join”., however, there is no “implode” function; instead, there is a built-in “join” function that performs the same task. In this article, we are going to examine JavaScript’s join function in some detail.

 Syntax

The join function concatenates the elements of an array into a single string. The syntax for the join function is as follows: array.join(separator) Here, separator is the string or string used to separate elements of the array; it can be any character or string, such as the space character (i.e., “ ”) or a string like “xyz”, but a comma is used as the default.

 Examples

Now, let’s look at some examples. First, we declare an array of letters. let arr = ["a", "b", "c", "d", "f"] We can call the join function for this array without providing a separator as follows, which will return the all characters from the array separated by commas: Now, let’s see what will happen if we provide the space character as a separator: Here, in the string returned, the array elements are separated by the space character instead of a comma. We can provide any character or string as a separator. If we want to put “ and ” between the array’s elements, we can do that as follows: Here, every alphabet is separated by the “ and ”, which might be very useful for certain applications. Any string can be provided as a separator for joining an array’s elements in the same way.

 Conclusion

This article explains JavaScript’s join function and provides some useful examples. We can provide any string we want as a separator to join an array’s elements. We hope you found this article useful and continue using linuxhint.com to learn about JavaScript.

Global Variables

JavaScript is a versatile yet functional language. Variables, which are key to any programming language, can be used to store values that can be accessed at any time. However, when using functions, there are certain factors related to the scope of the function that limit our ability to access a variable. We cannot access a variable if it is outside the scope of the function, and so the variables we want to use must have the proper scope upon declaration. To avoid issues related to scope, it is important to understand global variables. Therefore, in this article, we are going to discuss global variables and scope. The scope of a function can be considered as a boundary within which the function can be accessed. However, while a function does not know what is happening beyond the curly brackets that define it, a global variable can be accessed from anywhere in the program.

 Syntax

The syntax used to create a global variable, shown below, is no different than that used to create other variables. var variableName = value However, the location of this declaration is very important. We will explore this concept more fully by considering some examples.

 Example

First, let’s create a function called subtraction. function subtraction(a,b) { var subNum = 23;} In this function, we initialized a variable and assigned it a value. Now, we can try to access the variable in another function, i.e., division, and call that function. function division(a,b) { console.log(subNum);} division(); However, we get the following reference error because the variable subName is not defined within the correct scope. This error will occur any time we try to access subNum outside the function in which it is defined. For example: function subtraction(a,b) { var subNum = 23;}; console.log(subNum); Here, we still cannot access the variable because it is restricted to the subtraction function. However, let’s see what happens if we create the variable outside the function—for example, at the beginning of the script: var globalVar = 11; Now, let’s try to access it: console.log(globalVar); As shown below, we no longer get a reference error. Furthermore, globalVar should be accessible from any function. function division(a,b) { console.log(globalVar);} division(); As you can see below, globalVar is still accessible.

 Conclusion

In this article, we explained scope and global variables by using simple examples. We hope you continue learning JavaScript with linuxhint.com.

The Javascript for…in Loop

Javascript is one of the most popular programming languages in the world. In any programming language, loops have an essential value. Like many other languages, Javascript provides different loop syntax formats, as well. This article discusses an important Javascript topic known as the for…in loop. Sometimes, we may have to iterate through every single element of an object/array. But, we do not usually know the length of that particular object/array. The for…in loop even comes in handy when working with JSON. In this article, we will take a look at the for…in loop, its syntax, and some examples using this loop. Javascript’s for…in loop iterates through each property of the object.

 Syntax

The syntax of the for…in loop is as follows: for (const key in object) { // body of the for...in loop} where, The key is the variable used in each iteration. The object is the required object from which to iterate the loop. Next, we will go over some examples to reinforce the concept and show you how the process works.

 Examples

First, we see the simplest implementation of the for…in loop. In this example, we will first assume an object: let obj = { firstName: "John", lastName: "Doe"} And then, we will iterate through the object and console each property using the for…in loop. for (const name in obj) { console.log(name + " = " + obj[name]);} As you can see, the for…in loop has iterated through each property of the obj object and printed each property in the console, as we desired. Javascript also provides the built-in hasOwnProperty() function. We can perform the hasOwnProperty() check before performing any task in the for…in loop, like this: for (const name in obj) { if (obj.hasOwnProperty(name)) { console.log(name + " = " + obj[name]); }} This function comes in handy when you need to use JSON or for debugging purposes. When you do not know whether the key holds certain properties, you can also use the for…in syntax for the arrays, as well as for the strings. let arr = [23,24,25]for (const value in arr) { console.log(value + " = " + arr[value]);} Similarly, you can apply this syntax to the strings, as well. let str = "Linuxhint"for (const char in str) { console.log(char + " = " + str[char]);} But, it is not recommended to use the for…in loop for arrays and strings because there are dedicated loops and functions for arrays and strings. Like, for…of or Array.protptype.forEach() is for the arrays for doing the same tasks in better ways.

 Conclusion

In this article, you learned how the for…in loop works and how it helps with JSON and debugging. You also learned how to use the for…in loop with arrays and strings, although this loop is dedicated to and recommended for objects. But, I hope this article proved helpful to your understanding of the for…in loop and its various implementations. To learn more about Javascript, you can find more articles at linuxhint.com.

Javascript Regular Expression

Many programmers are familiar with the notion that the regular expression is a useful yet underrated concept. But, they do not know very well how to use regular expressions efficiently. Regular expressions are used in not only Javascript but almost all other programming languages. In this article, you will learn about regular expressions step by step. It should be easy for programmers of any level to understand the concepts covered in this article. A Regular Expression is an object in which patterns are given to match with the desired string.

 Syntax

The syntax for a regular expression is very simple, and can be written as follows: /pattern/flags A pattern is a string in which you provide a pattern to match another string.Flags are optional attributes that serve varied purposes. For example, the flag “g” stands for “global,” among many others. The scope of regular expressions is very broad. We will show you the basic ones that are most necessary for programming through a step-by-step explanation and some real-life examples. There are a lot of methods in which you may need to use regular expressions, for example,’s search(), replace(), match(), and split() methods. We will start with a simple string search without using the regular expression, and later, we will show you how to perform the same search using regular expressions.

 Examples

We will first suppose the string: let str = "Linuxhint is great. linuxhint is working great and performing 100%." We have repeated the same word “great” and “linuxhint” in the phrase. The purpose of this weird string will become obvious in a moment. Alright! Now, we will simply write the Javascript search string method to search for the term “work” str.search("work"); As you can see, it shows the index from where the given substring “work” began. Now, we will move on and try doing the same thing with the regex syntax.

 Step 1: Search and Replace a Substring

You can search for a matching string using a regular expression by simply placing the substring between the two slashes in the expression. str.search(/work/); As you can see, it has also given us the same output. Alright! Now, we will see what we can do with the regular expression. Let us try to replace the word “great” with, say, “awesome” using the replace() method. str.replace("great", "awesome"); Here, you can see the problem: the first occurrence of “great” has been replaced, but the second one has not. In the first step, you simply learned how to search for a string using a regular expression. Now, we will move towards the next step and learn about the concept of flags.

 Step 2: Flags

In this step, you will learn more about the concept and purpose of flags in regular expressions. We will use Javascript’s replace method to explain this idea. If you want to replace all the occurrences of “great,” you can use the regular expression with the ‘g’ flag, which is short for global. str.replace(/great/g, "awesome"); Perfect, all the occurrences of “great” are now changed. But, you may face a problem if you try to change all the occurrences of “linuxhint” to, say, “our website” using the same technique. We will try to do that first, then we will see how can we resolve this issue. str.replace(/linuxhint/g, "our website"); Although we have provided the global flag with the regular expression, the first occurrence does not change. This is because of case-sensitivity. So, we will also need to provide the case-insensitivity flag ‘i,’ in this case. You can do this simply by adding the ‘i’ flag along with the ‘g’ flag. str.replace(/linuxhint/gi, "our website"); Great. As you can see, all occurrences of the term “linuxhint” have been changed to the term “our website,” regardless of the case-sensitivity. Similarly, you can use regular expressions’s split() function. str.split(/linuxhint/gi); Alright! The function worked fine. The split() method has returned the array of substrings, based on the “linuxhint” term. But, if you want to include the separators, as well, in the array of the substring, you will have to play with the patterns. So, in this step, we have learned about the flags and how they help us. There are more flags available. For example, “m” is for multiline matching, “s” is for dot all, etc. Now, we will move on to the concept of patterns and learn how to use these items.

 Step 3: Patterns

In this step, you will learn how to utilize the patterns and related options. To include the separators in the array of the substring, simply add parentheses around the pattern, as can be seen in the following image: str.split(/(linuxhint)/gi); Perfect! As you can see, the separators are also included in the array of substrings. To split the base of two separators, you can give multiple substrings in a regular expression using the OR “|” operator. str.split(/linuxhint|great/gi); All right! The operator worked great, as we expect it to split.

 Backslash

Now, to split between the base of the space “ “ or the dot “.” meaning to add special characters in the regular expression, add a backslash “\” before any special characters. str.split(/\ |\./gi); Okay, so far, so good. For example, say, you want to change the dots into commas in the following expression: str.replace(/\./g, ","); It worked! Backslashes are also used for another purpose. To search any word, digit, or space, you can use \w, \d, and \s, respectively. For example, to replace spaces with dashes, the following expression is used: str.replace(/\s/g, "-"); Awesome! You can really see the potential in regular expressions, now.

 Square Brackets [ ]

If you want to replace multiple characters in a string, you can provide all of them in a single square bracket, and they will be replaced by the given substring. For example, if you want to replace three letters in a string and you do not want to put a lot of OR “|” operators in the regular expression, you can use square bracket syntax, in which you can give multiple letters, like this: str.replace(/[nia]/g, "u"); You can even give a range of letters, like this: str.replace(/[g-l]/g, "u"); Or, a range of numbers: str.replace(/[0-5]/g, "9"); And, if you want to exclude the provided characters in the square brackets, you can use the caret character, like this: str.replace(/[^g-l]/g, "t"); This comes in handy when getting data from users and testing and validating that data, especially in email, phone, or date validation.

 Conclusion

This article has just scratched the surface of the Javascript regular expression. It covers the concepts only from the beginner to the intermediate level. There is a lot more to learn about the regular expression, and you can use this expression to do a lot of things that you may have not even thought of. To keep on learning, working, and getting more experience, check out more articles on this topic at linuxhint.com.

Javascript String Length

Javascript is a scripting or programming language that is quickly becoming one of the most widely used programming languages in the world. Strings are a crucial part of all programming languages. Programmers often need to use strings to manipulate or manage data. Javascript’s built-in functions or properties for manipulating strings can come in handy. For example, if you are getting some user data in form fields in HTML and you want to restrict the length of a string while showing some data on a webpage, Javascript’s built-in string length property can help you in this case. This article shows you what the string length property is and how you can use it in a few different scenarios. The string length property fetches all the characters included within a string.

 Syntax

The syntax for the string length is as follows: string.length This property simply gives back the total characters available in the string at run time. Let us try out a couple of examples that use the string length property.

 Examples

First, you will see the basic implementation of this property. Later, you will see its application. Suppose you have the following string: let str = "Linuxhint is great." If you want to know the number of characters in this string, simply apply the string length property as follows: str.length As you can see, this simply returns the length of the specified string. You can use this property in multiple places. For example, say you are doing a check-in on an “IF” statement, like the one below: if (str.length <= 20) { console.log("It's a short string");} else { console.log("It's a long string");} And, as you can see in the console output, the statement “It’s a short string” is printed. That is great. You can use this in the conditional statement of the for loop, as well. If you want to iterate from each of the characters in a string and convert every letter into a lower-case letter, but you are not yet aware of how many characters the string has, then you can simply give the str.length property as a conditional statement. for (let i = 0; i < str.length; i++) { console.log(str[i].toUpperCase());} As you can see in the output console, every character is shown in the console separately and converted into uppercase letters, as well. So, this is how you can apply it to a lot of different scenarios according to your needs.

 Interesting Fact

Here is an interesting fact for you guys. Let us now try to dodge the string length property by assigning it a numeric value. You will see that it will either print the assigned value or the real length of the string. So, first, assign it a value str.length = 10; And now, we will try to console the length of the string. console.log(str.length); And, as you can see, it does not show the assigned value. It shows that the length of the string or the number of characters in the string are being calculated at run time, and then it displays the output.

 Conclusion

In this article, you learned what the string length property is and you have seen its applications in a few different examples. I hope this article proved helpful in understanding the string length property and its implementations. You can read on to learn more about Javascript at linuxhint.com.

Javascript toLowerCase Function

Javascript is a popular scripting or programming language. Programmers often use Javascript to manipulate or manage data. For example, say, you are getting some data from a user in the fields of an HTML form. While getting the data from the user, you cannot control what the user is typing. But, you also need to show the data in a good format. Users may input capital letters where they are not needed or vice versa. While saving data to the database or showing data to a web page, as a programmer, it is necessary to take care of this function. For this purpose, we have Javascript’s built-in function toLowerCase() for converting a string to lower-case letters.

 Syntax

The syntax for Javascript’s toLowercase() function is as follows: string.toLowerCase(); The toLowerCase() function converts all the alphabets in a string into lower-case letters. This function does not change the original value of the variable. Instead, the function creates a new string for the instance. In this way, the function does not take any arguments, although the parentheses “()” are used for taking arguments. But, with the toLowercase() function, you follow the same conventions of a function. Let us now look at some examples.

 Examples

Suppose there is a string that includes some uppercase and lowercase letters, such as the following string: let str = "Welcome to thE LinuxHint." But, we need to convert the string entirely into lower-case letters. So, we will simply apply the following: str.toLowerCase(); As you can see, the string has been converted to a formatted string. All the letters are now in lower-case format. It is as simple as that. This function is for the string. But, this is not only restricted/limited here. We can apply the function to an array of strings and even to an array of objects containing strings, as well. Let us take a look: First, we will write down the array of strings, as follows: let arr = ["Hi", "LinuxHint", "GREAT"] Now, to change the term “GREAT” to all lowercase letters, we will apply the following: arr[2].toLowerCase(); where ‘2’ is the index of “GREAT”. As you can see, now, the term “GREAT” has been converted into lower-case letters. We did something similar for two other strings: [0] for the term “Hi” and [1] for the term “LinuxHint.” Let us now see how we can apply this function to an array of objects in which the objects contain the string, as follows: let arr = [{"name":"John"},{"name":"BOB"},{"name":"Ivan"}] To convert the term “BOB” to all lower-case letters, we will change it as follows: arr[1].name.toLowerCase(); Awesome. As you can see, we can do a lot with Javascript’s toLowerCase() function.

 Conclusion

In this article, we showed you how to convert string characters to lower-case. We also showed you how to apply the same function to an array of strings and an array of objects containing strings. I hope that this article proved beneficial for converting an informal string into a cleaner and more formal-looking lowercase string. You can learn more about Javascript at linuxhint.com.

Javascript split

Javascript is a scripting or programming language of the web. Strings are an important part of the variables in any programming language. We often need to manipulate string according to our needs. In this article, we will talk about the javascript’s split string method which is used to split the string according to our needs. So, let’s take a look at what is a string and what does split string method do. The string is just a simple text or characters which can include the alphabets, numbers, or symbols. Javascript’s split() method is called upon when it is required to split the string into the array of substrings in accordance to the separator that you provide.

 Syntax

Let’s have a look at the syntax of the split method. string.split([seperator][, limit]); Here, the separator could be a single character using which you would like to split the string. And the limit is the limit of splits. When the number of substrings becomes equal to the limit, the split() method stops. Let’s dive in and get a couple of examples done for the understanding of the split() function.

 Examples

We suppose a string “Linuxhint is great and working hard to grow.”. Now, let’s try to split the string into arrays of string using the split() method. By providing the “ ” space character as a separator. But, without providing the limit. Later, we will do it with the limit. linux.split(" "); As you can see that the split() method has returned the array of substrings, based on the “ ” space. Now, let’s see what happened if we provide a limit as well. linux.split(" ", 3) As you can see that the split() function stopped splitting the string, and it would stop splitting the string when the count is equivalent to the number of substrings. Now, let’s see if we don’t provide a separator just an empty string, and calls the split() function. linux.split(""); As you can see that the function has split and returned the array of each character separated. Now, let’s see if we don’t provide both of the arguments and just calls the split() function. linux.split(); Great, the split() function has returned an array with a single substring in it that is the whole string

 Pro tip

What if we want to split the string on the base of two separators or we want separators as well in the output array of substring? Luckily, there is a solution as well, We can provide regular expressions as a separator as well. So, let’s see how can we split the string with two separators. Space “ “ character and “i” character linux.split(/\ |i/); Alright! It worked great. As we expect it to split. Now, what if we want to include the separators as well in the array of the substring. We will simply add parenthesis() around the regular expression. linux.split(/(\ |i)/); Perfect, as you can see that the separators are also included in the array of substrings.

 Conclusion

In this article, we have seen that how can we split a string on the base of a separator provided and how can we apply the limit to the split() function. We came across how we could provide regular expressions in compliance with our needs and requirements. So, have a happy and the best learning of javascript with linuxhint.com.

Javascript replace

Javascript is a scripting or programming language of the web. Strings are an important part of the variables in any programming language. We often need to manipulate or extract some specific string according to our needs. You must have seen it often at a lot of websites that on a click of a button or something the text got changed. How can we find and replace some specific words in a long paragraph? Do we have to change all the code? Of course not, we have a replace() method to replace the substring with a new provided string. So, let’s take a look at what is a string and how can we replace a substring with another string. The string is a simple text or characters which can include the alphabets, numbers, or symbols. Javascript’s replace() method finds the provided substring and change/replace that substring with a new provided string.

 Syntax

Syntax for the replace() method is string.replace(substring, newstring); substring can be any value from the string to which we want to replace newstring is the value that replaces the substring(first parameter).

 Examples

Now, if we take a look at some examples. We suppose a string “Linuxhint is great and linuxhint is working great.”. In this string, I have repeated the same word “great” and “linuxhint” intentionally. The purpose of this will be right in front of you in a moment. Now, let’s try to replace the word “great” with let’s say “awesome” using the replace() method. linux.replace("great", "awesome"); Here you can see the problem that the first occurrence of “great” gets replaced. But, the second one doesn’t. So, here comes the concept of the regular expression. We can also give the regular expression instead of the substring to the replace() method. So let’s modify the syntax a little bit that we can give regular expression as well. string.replace(substring|regex, newstring); regex is a regular expression object. The matches will be replaced by the newstring. If we want to replace every single occurrence of the word “great” then we shall pass the regular expression with a ‘g’ flag, which is a short form for global. Take a look below to get an idea about what exactly I mean. linux.replace(/great/g, "awesome"); Perfect, all the occurrences of “great” are changed. But, now we may face a problem if we try to change all the occurrences of “linuxhint” to let’s say “our website” using the same technique. Let’s try to do that first, then we will see how can we resolve that. linux.replace(/linuxhint/g, "our website"); As you can see that. Although we have provided the global flag with the regular expression. But, the first occurrence doesn’t get changed. This is because of case-sensitivity. So, we need to provide a case-insensitivity flag ‘i’. We can do that by simply adding the ‘i’ flag along with the ‘g’ flag. Like, linux.replace(/linuxhint/gi, "our website"); Great. As you can see that all the occurrences of “linuxhint” are changed regardless of the case-sensitivity.

 Pro tip

We have two protips for you. One is that we can give multiple substrings in a regular expression as well using the OR “|” operator. The second one is that we can also provide a function instead of the newstring. So, the final syntax that you should take with you is string.replace(substring|regex, newstring|function); Let’s have a look at an example. To understand how it works. In this example, we will change/replace both “great” & “linuxhint” using a single replace method and later we will provide some tasks to do in a function, in which we will change the matches to the uppercase. linux.replace(/great|linuxhint/gi, (m)=>{return m.toUpperCase()}); Alright! As you can see that both of the words “great” & “linuxhint” are converted into the uppercase letters, successfully.

 Conclusion

In this article, we have learned that how can we use the replace() method to replace the substring and how can we use the regular expression to give multiple values along with the global and case insensitive flag. I hope this article has helped you to thoroughly understand the replace() method. So, keep on learning javascript with linuxhint.com.

Javascript String to Int

Javascript is a language of the web and managing data is an important aspect of any programming language. We often need to manipulate or manage variables according to our needs. Sometimes we need to perform arithmetic operations so, we can’t do that with strings. We need integers to do that. Since Javascript is a language of the web now. Speed optimization has become very important in this era. We have to think and manage every single byte if we can. We must know and care about memory because the strings take more memory than integers. We need to keep things very simple. But, what if we have to perform some arithmetic operations. If, variables are in string type. Do we have to reinitialize the variable with integer type? Of course not! It will even take more memory. But, what if we have a function that will convert or parse the string into the integer and we can perform our tasks. So, in this article, we are gonna see that how can we convert or parse a string into the integer using the parseInt() function. The parseInt() is a function to which we can pass a string as an argument and it will return us an integer if it exists. This function returns NaN(Not a Number). If, no number found in that string. This function also returns NaN if there exists any character before the number.

 Syntax

Let’s take a look at the syntax of the parseInt() function. parseInt(value [, base]); Here, Value is the string that we want to parse into the integer. And the base is the base number of the provided string to which we want to convert into a decimal number. It is an optional value. Let’s have look at a couple of examples to understand more clearly.

Examples

parseInt("34"); // 34</td> Now, let’s try to give a float number. parseInt("34.53"); // 34 As you can see. It only prints the 34. Let’s try to put a space before or after the number. parseInt(" 34 "); // 34 It worked fine. But, if we put any character before the number. parseInt("the 34"); // NaN It prints NaN(Not a Number). The same applies to the empty string.

 Pro tip

Now, what if we try to give the base number along with the value. Like, the base of the binary number system is 2. parseInt("34", 2); // NaN Ok, since 3 and 4 are not the numbers of a binary number system. It prints NaN. Now if we provide it a true binary number. It should print the decimal number against that binary number. parseInt("10011011", 2); // 155 Here comes an interesting thing about this function. Like, if we keep on providing the binary number 0’s and 1’s. It will keep on converting that number into the decimal number system. But, when we start to give a non-binary number system. It will stop right there and won’t convert any further. But, until we keep on giving the binary numbers. It keeps on converting. parseInt("100110113432", 2); //155 Alright! We can also do the same tasks with the Octal number system and Hexadecimal number system using the parseInt() function.

 Conclusion

In this article, we have learned that how can we use the parseInt() function to convert the string into an integer. We have also learned about some exceptional cases of the parseInt() function and how does it help in converting the number systems as well. I hope this article was beneficial and helpful for understanding the conversion of strings into integers. So, keep on learning javascript with linuxhint.com.

Javascript Substring

Javascript is a scripting or programming language of the web. Strings are an important part of the variables in any programming language. We often need to manipulate or extract some specific string according to our needs or somewhere we don’t have to show all the text. You must have seen some data (if we specifically talk about strings) on the web that are not fully shown on the screen. How did that happen? How can we get some specific part of a string? So, let’s take a look at what is a string and how we can take a substring of that string.

 String & substring

A string is simply a text or characters which can include alphabets, numbers, or symbols. A substring, as it’s in its name. A subpart of a String. If we talk about string. Javascript has some built-in functions for manipulating string. One of them is substring() a function that serves our purpose. If we want to extract some specific parts from a string. We can use substring() function.

Syntax:

The syntax for the substring() function is string.substring(startIndex, endIndex); startIndex is the index from where you want to start the string. endIndex is the index where you want to end the string.

Examples:

If we suppose a string, like “linuxhint”. We want to just get the “Linux” from the “linuxhint”. So, we will do that using substring() function like this name.substring(0, 5); // “linux” Now, if you notice that it doesn’t include the 5th index element. But, it picked the 0th index element. Which implies that startIndex gets included. While endIndex doesn’t get included. So, now if we want to pick the “hint” from “linuxhint”. Although there are only “0” to “8” indexes. But, we will give “9” as a value to the endIndex. name.substring(5, 9); // “hint” We can give it only one value as well. name.substring(5); // “hint” It will start from that index and continues until the end of the string. Alright! Now, we have seen the syntax and how does it work. Let’s see some of its exceptional cases.

 Exceptional Cases

Let’s try to give a startIndex greater than the endIndex and some negative values to see how does it respond. startIndex > endIndex If we give it a startIndex greater than the endIndex. name.substring(5, 2); // “nux” It has swapped both values and printed the string from the 2nd index to the 5th index. So, if we write either name.substring(5, 2) or name.substring(2, 5). //both will print the same output name.substring(5, 2); // “nux” name.substring(2, 5); // “nux”</td> It will print out the same output.

 Negative values

substring() function doesn’t take negative values. If we give it a negative value. Since there is no negative index. It takes it as a “0”. Either we give a negative value to the startIndex or the endIndex. This function considers it a “0”. name.substring(-5, 2); // “li” If we give a negative value to the endIndex. The function will swap the values. Because negative value will be converted to “0” and “0” will be the lowest value. name.substring(5, -2); // “linux” And, if we give a negative value to both of the indexes. The function will print an “” empty string. name.substring(-5, -2); // “”

 Pro tip

By the way, here is a pro tip. We can use string.length function within a substring() function. name.substring(5, name.length); // “hint” Or we can give it a string.length – [value], like name.substring(5, name.length - 1); // “hin”

 Conclusion

So, after reading this article, you should have a profound knowledge of the substring() function. Because you have learned all about the substring() function. All of its exceptional cases and how can we manipulate the string according to our needs. So, have fun with the strings.

Connecting MySQL with NodeJS

MySQL server is a very popular database server and it is supported by mostly used programming languages, such as PHP, Python, Perl, Java, C#, etc. It is an open-source application, so anyone can download this application for storing, retrieving, updating and deleting data by using database queries. You will require the server and client packages to be installed in your system to perform different types of database operations in the database server. MySQL server is now becoming popular for Node developers also. Node developers start using MySQL server with MongoDB for some special features of the MySQL server. How you can make a connection with MySQL server using the node-mysql client is shown in this tutorial.

Prerequisite:

Before starting this tutorial you have to confirm that MySQL server and client packages are installed and working properly in your system. If you install the MySQL server for the first time then the password of root user is empty by default. But you have to set the password for the root user to make a connection with MySQL server using the node-mysql client. You can check this tutorial to know how to change the root password of the MySQL server. Run the following commands to work as a root user and connect with MySQL server by using MySQL client. $ sudo -i $ mysql -u root -p Enter the root password and run the following SQL commands to create a new database, create a table on that database and insert some records in that table. The following command will create a database named mydb. CREATE DATABASE mydb; The following command to select the database for doing database operations. use mydb; The following command will create a table named book in the database mydb. CREATE TABLE book ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(50) NOT NULL, author VARCHAR(50) NOT NULL, price int(5)); The following command will insert four records into book table. INSERT INTO book values (NULL,'Learning PHP and MySQL', 'Robin Nixon', 45), (NULL,'Learning JQuery', 'Jonathan', 35), (NULL,'Angular in Action', 'Jeremy', 50), (NULL,'Mastering Laravel', 'Christopher', 55);

Install mysql client for nodejs:

Run the following command to check nodejs is installed in the system before running the command of installing mysql client of nodejs. It will show the installed version of nodejs. $ node -v If it not installed then you have to install it by running the following command. $ sudo apt-get install nodejs You will require another package named npm to be installed in the system to install mysql client for nodejs. If it is not installed before run the following command to install npm. $ sudo apt-get install npm Now, run the following command to update the system. $ sudo apt-get update The following command will install mysql module for nodejs that will work as mysql client. $ npm install mysql

Simple MySQL connection using NodeJS:

Create a JS file named connection1.js with the following script to make a connection with the previously created database named mydb and read data from book table. mysql module is imported and used for creating a simple connection with the MySQL server. Next, a query will be executed to read all records from book table, if the database is connected properly. If the query executed properly then all records of book table will be printed in the terminal and the database connection will be closed. connection1.js // Import mysql module let mysql = require('mysql');// Setup database connection parameter let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '1234', database: 'mydb'});// Connect with the database connection.connect(function(e) {if (e) {// Show error messaage on failurereturn console.error('error: ' + e.message);}// Show success message if connected console.log('\nConnected to the MySQL server...\n');});// Set the query message $query = 'SELECT * from book';// Execute the database query connection.query($query, function(e, rows) {if(e){// Show the error message console.log("Error ocurred in executing the query.");return;}/* Display the formatted data retrieved from 'book' table using for loop */ console.log("The records of book table:\n"); console.log("Title\t\t\t\t Author\t\tprice\n");for(let row of rows) { console.log(row['title'],"\t\t",row['author'],"\t","$",row['price']);}});// Close the database connection connection.end(function(){ console.log('\nConnection closed.\n');}); Output: Run the following command to execute the script. $ node connection1.js The following output will appear after running the script.

Pooled MySQL connection using NodeJS:

Making a simple MySQL connection with NodeJS using mysql module is shown in the previous example. But many users can connect with the database server at a time through the application when the application is created with MySQL database for production purposes. You will require the express module to handle concurrent database users and support multiple database connections. Run the following command to install the express module. $ npm install express Create a JS file named connection2.js with the following script. If you connect with MySQL with the following script then 10 concurrent users will be able to make a connection with the database server and retrieve data from the table based on the query. It will make a connection at the port 5000. connection2.js // Import mysql modulevar mysql = require('mysql');// Import express modulevar express = require("express");// Define object of express modulevar app = express();// Make database connection to handle 10 concurrent usersvar pool = mysql.createPool({ connectionLimit :10, host : 'localhost', user : 'root', password : '1234', database : 'mydb', debug : true});/* Make pooled connection with a database and read specific records from a table of that database */function handle_database(request,response) {// Make connection pool.getConnection(function(e,connection){if (e) { //Send error message for unsuccessful connection and terminate response.json({"code" : 300, "status" : "Database connection errror"}); return;}// Display success message in the terminal console.log('Database connected');// Read particular records from book table connection.query("SELECT * from book where title like '%PHP%' or title like '%Laravel%'",function(e,rows){ connection.release();if(!e) { // Return the resultset of the query if it is successfully executed response.json(rows);}});// Check the connection error occurs or not connection.on('error', function(e) { response.json({"code" : 300, "status" : "Database connection errror"});return;});});}// Call the function for making connections app.get("/",function(request,response){- handle_database(request,response);});// Listen the connection request on port 5000 app.listen(5000); Output: Run the script from the terminal like the previous example. It will wait for the connection request after running the script. $ node connection2.js Now, open any browser and go to the following URL to send a connection request. http://localhost:5000 The following output will appear as a response after executing the query. If you open the terminal now then you will see the following output. Ten connection requests can be sent at a time from 10 browsers in the way mentioned above.

Conclusion:

The most simple ways to work with MySQL and NodeJS are shown by two examples in this tutorial. If you are a new Node developer and want to work with MySQL database then I hope you will be able to do your task after reading this tutorial.

Simple NodeJS Application

In the last couple of years, the world has undergone some fascinating technological changes. Each day, something new is developed that offers an improvement over its predecessor and gives us access to a whole new dimension. One certain region that has seen a significant improvement in its features and popularity is the web development sector, particularly NodeJS, which has become many developers’ first choice for back-end development.

What actually is NodeJS?

NodeJS is an open-source JavaScript platform used for developing and executing back-end services called APIs (Advanced Programming Interfaces). These are the services that power up the client applications such as web apps that run on the browser and mobile applications. NodeJS is important because these client applications are just a surface for users to see and interact with. In addition to this, they need to talk to some service on the server or in the cloud for the storage of data, sending emails or pushing notifications. This is where NodeJS comes into the picture which allows users to create server-based applications and produce real time back-end services that can be used to power up client applications. Being highly scalable and superfast, NodeJS is a great choice for development and hence today we’ll be looking at how to make a simple NodeJS application.

Step 1: Installing NodeJS

Before moving on the development phase, let us first see how to install NodeJS on our Linux based desktops. There are actually multiple ways to install NodeJS on a Linux based computer. We, however, will only be looking at two methods of installing NodeJS.

Step 1(a): Installing NodeJS using NVM

In this method, we will be using the Node Version Manager (NVM) to install NodeJS. A huge benefit of using this is that there are no permission issues for using NodeJS. First of all, we have to install nvm which can be done by the following command: $ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash This command adds nvm to your path profile and extracts all the nvm data in the directory ~/. nvm To check whether nvm has been installed correctly, restart the terminal and run: $ command -v nvm If you see nvm as the output, then it has been successfully installed. Now we’ll be installing NodeJS and npm which is basically an ecosystem of NodeJS libraries. To do this, simply run the following command that will install the most recent version of NodeJS: $ nvm install node You can also install any specific version of NodeJS that you want to install. For this tutorial, we’ll be installing the version 12 of NodeJS. $ nvm install v12.16.1 Once installed, you can check your NodeJS and npm installed versions by running the following commands: $ node -v $ npm -v

Step 1(b): Installing NodeJS using Ubuntu official repository

One huge advantage of installing NodeJS in this way is that Ubuntu has a stable version of NodeJS in its official repository. First of all, the following command will be run to update our system’s apt cache and packages to the latest versions so that no issues arise during installation: $ sudo apt-get update Next, we will be installing NodeJS with the following command: $ sudo apt install nodejs Once installed, you can check your NodeJS installed version by running the following command: $ node -v In this method, we also have to install npm, the ecosystem of NodeJS libraries. This can be done by inputting the following command into the terminal: $ sudo apt install npm Similarly, you can check your npm installed version by running the following command: $ npm -v

Step 2: Coding a NodeJS Application

For this tutorial, we’ll be creating a simple HTTP Server which will listen to the client on port number 8080 and output Hello World as a response to the client. The following is the complete code: let http = require('http') server = http.createServer(function(request, response) { response.write('Hello World') response.end()}) server.listen(8080) console.log ("Server Running") Let us now look at each line of code to understand what is actually happening here.

Code Explanation:

In Node JS, there are some built in modules available. These are functions that have already been defined in NodeJS and provide certain functionality in our applications. These modules can be imported using the require keyword. let http = require('http') In the first line of our code, we are importing the HTTP built in module of NodeJS. The HTTP module is used here so that we can create a server in our application that can listen for HTTP requests on a given port. server = http.createServer(function(request, response) Over here, we use a method of the HTTP module called createServer which, as the name says, creates a server instance. In this, we pass a function through here which takes up two parameters – a request object and a response object. Now whenever a request is made to our server, this function will be called. The response object comes loaded with details about the request that has been made and the response object is something that we can use to send a response back to the client. response.write('Hello World') response.end() Over here, response.write is used to write a response to the client. This is how things can be printed on the browser. In this case, this will allow us to print Hello World on the browser. The response.end() lets the browser know that the request has ended and sends the response to the browser. server.listen(8080) console.log ("Server Running") The server.listen function is used here by our server to listen to the client on port number 8080. It is important to note that any port that is available can be used here. The last line console.log is used to print anything on the terminal. In this case, we are printing Server Running so that we know the server has started.

Step 3: Running and Testing our NodeJS Application

Now that we have our code written and understand what is happening in it, let us now run it and test whether it is working or not. To do this, open the directory, where you have saved your file containing the above NodeJS code and along with this, also open the terminal. In order to run a NodeJS file, simply type in the following command in the terminal: $ node filename.js filename here refers to the name of your file. In my case, I’ve stored my code in a file called sample.js. See below: $ node sample.js Now our server seems to be running. Let us now check to see if our response has been sent to the client. To do this, open your browser and enter localhost: port. In my case, I’ll be running the command: localhost:8080. See the image below for better understanding: We can clearly see our output Hello World displayed on the page. Voila, we were successful in creating a simple NodeJS Server.

Why use NodeJS over its Alternatives?

In today’s world, JavaScript has completely changed the face of web development. This has thus led to NodeJS becoming a popular choice for back-end development. Along with using JavaScript as its core, NodeJS is highly fast, extremely flexible and great for prototyping and agile development. Moreover, using NPM (Node Package Manager) as its ecosystem which is the largest ecosystem available for open-source libraries, it grants multiple tools and modules to developers which further increases its demand. All these reasons make it a great choice for web development.

How to install the latest Node.js on Linux?

Node.js is a runtime JavaScript environment that is used on the server-side. Node.js is a full-stack software building solution but is mostly used at the back end to build the applications. Node.js uses the NPM package manager as a default package manager, which is known as the most used software registry. There are several methods to install Node.js on Ubuntu 20.04 LTS, but here, we will learn the two most efficient and easiest methods to install it. Using APT package repository Using the APT package repository through NodeSource PPA Let’s get started with the easiest one.

 Install Node.js on Ubuntu 20.04 using APT

Installing any software through the APT package repository is the easiest way to install the software on Ubuntu. First, update the system’s package repository. $ sudo apt update Then, install the Node.js using the simple apt install command with the sudo privileges. $ sudo apt install nodejs -y In this command, the “-y” flag is added to automatically answer “yes” if any prompt occurs. After installing the Nodejs, if you want to install NPM as well, run the command. $ sudo apt install npm -y After a while, NPM will be installed as well. The above two commands will install all the other tools required for compilation. To verify and check the versions of the Node.js and NPM, execute the following two commands. $ nodejs --version $ npm --version As you can see, version 10.19.0 of Node.js and version 6.14.4 of NPM is installed.

 Install Node.js on Ubuntu 20.04 through NodeSource PPA

In case you want to install some specific or older version of Node.js, it is better recommended that you use the official Private Package Archive(PPA) managed by the NodeSource. At the date of writing this post, NodeSource has the following Node.js versions available: Node.js v15.x Node.js v14.x Node.js v12.x Node.js v10.x Furthermore, you can check the version provided by the NodeSource by visiting their Github page (GitHub – nodesource/distributions: NodeSource Node.js Binary Distributions). For example, to install the Node.js v15.x, you first need to have the curl installed on your system. To install curl, perform the following. $ sudo apt install curl -y After installing the curl, execute the following command to run Nodesource’s installation script using the curl command. $ curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash - Once the NodeSource’s PPA is configured for Node.js on your system, now install the Node.js by typing the following command. $ sudo apt install nodejs -y Let’s verify the versions of Node.js and NPM by typing the commands. $ node --version $ npm --version You can witness that the required versions are installed successfully.

 Wrap up

These are the two different methods to install Node.js on Ubuntu 20.04 LTS. You can either install it via the APT package repository, which is the easiest way, or go with your desired version with the official PPA introduced by NodeSource.

Installing Node.js on CentOS 8

In this article, I am going to show you how to install Node.js on CentOS 8. So, let’s get started.

Installing Node.js using Package Manager:

Node.js is available in the official package repository of CentOS 8. So, you can easily install it on CentOS 8 using DNF or YUM package manager. First, update the CentOS 8 package repository cache with the following command: $ sudo dnf makecache The CentOS 8 package repository cache should be updated. Now, to install Node.js and NPM package manager on CentOS 8 from the official package repository of CentOS 8, run the following command: $ sudo dnf install nodejs npm Now, to confirm the installation, press Y and then press <Enter>. Node.js and NPM should be installed. Once Node.js and NPM is installed, check whether Node.js is working correctly as follows: $ node --version As you can see, Node.js v10.16.3 is installed. Also, check whether NPM is working correctly as follows: $ npm --version As you can see, NPM v6.9.0 is installed. The same way, check whether NPX is working as follows: $ npx --version As you can see, NPX v6.9.0 is installed.

Installing Node.js Manually from the Official Website of Node.js:

The version of Node.js and NPM in the official package repository of CentOS 8 is old. At the time of this writing, the latest LTS version of Node.js is v12.13.0 and the latest version of Node.js is v13.0.1. If you want to install the latest LTS version of Node.js or the latest version of Node.js on CentOS 8, you will have to download Node.js from the official website of Node.js and manually install it on CentOS 8. First, visit the official website of Node.js. Once the page loads, click on the LTS version button if you want to install the latest LTS version of Node.js. Otherwise, click on the Current version button if you want to try out the latest version of Node.js. Your browser should prompt you to save the file. Select, Save File and click on OK. Your browser should start downloading the Node.js archive. It may take a while to complete. If you’re using a headless version of CentOS 8, then visit the official website of Node.js from any browser. Once the page loads, right click (right mouse click) on the download button and copy the download link. Now, SSH into your CentOS 8 machine and use wget to download the Node.js archive file using the link that you’ve copied earlier as follows: $ wget https://nodejs.org/dist/v12.13.0/node-v12.13.0-linux-x64.tar.xz Once Node.js archive file is downloaded, navigate to the directory where the archive file is downloaded (usually ~/Downloads) as follows: $ cd ~/Downloads The Node.js archive file should be there. $ ls -lh Now, you have to extract the Node.js archive file. I will extract it in the /opt directory. If you want, you can extract it to some other directory. Just replace /opt with the directory path where you want to extract the Node.js archive file. To extract the Node.js archive file in the /opt directory, run the following command: $ sudo tar xvJf node-v12.13.0-linux-x64.tar.xz -C /opt Node.js archive file should be extracted in the /opt directory. Once the Node.js archive file is extracted, a new directory (node-v12.13.0-linux-x64 in my case) should be created in the directory where you extracted it. $ ls /opt Now, you have to add the path of Node.js to the PATH environment variable in order to access Node.js, NPM and NPX binaries easily. You can create a shell script in the /etc/profile.d/ directory which will automatically update the PATH environment variable every time your CentOS 8 machine boots. To create a new shell script /etc/profile.d/node-v12.sh, run the following command: $ sudo vi /etc/profile.d/node-v12.sh Now, press I to switch to the Vi INSERT mode and type in the following lines of codes in the node-v12.sh file. export NODE_VERSION=v12.13.0export NODE_DISTRO=linux-x64export NODE_HOME="/opt/node-${NODE_VERSION}-${NODE_DISTRO}"export PATH="$PATH:${NODE_HOME}/bin" NOTE: By the time you read this article, new versions of Node.js may be released. So, make sure to change NODE_VERSION from v12.13.0 to the version of Node.js you’re trying to install. If you’re extracting the Node.js archive file to some other directory than /opt, then change /opt to the directory you’re extracting the Node.js archive file. The final shell script file should look as follows. To save the file node-v12.sh, press <Esc> to switch to Vi COMMAND mode, type in :wq! and then press <Enter>. Now, reboot your CentOS 8 machine with the following command: $ sudo reboot Once your CentOS 8 machine boots, verify whether the shell script set all the Node.js environment variables correctly with the following command: $ env | grep NODE As you can see, the Node.js environment variables are correctly set. Now, check whether the PATH environment variable is updated correctly with the following command: $ echo $PATH As you can see, the Node.js binary path is in the PATH environment variable. Great! Now, check whether Node.js is working correctly with the following command: $ node --version As you can see, the version of Node.js installed is v12.13.0. So, it’s working Also, check whether NPM is working correctly with the following command: $ npm --version As you can see, the version of NPM installed is 6.12.0. It’s working as well. Lastly, check whether NPX is working correctly with the following command: $ npx --version As you can see, the version of NPX installed is 6.12.0. It’s also working. So, that’s how you install Node.js on CentOS 8. Thanks for reading this article.

Installing Node.js using Package Manager:

Installing Node.js on Debian 10

Node.js is a server side JavaScript runtime. Node.js is open source and cross platform. Node.js runs on Linux, Windows and macOS. It is mainly used to develop software APIs and networking applications. In this article, I am going to show you how to install Node.js on Debian 10 and how to run a simple Node.js program on Debian 10. So, let’s get started.

 Installing Node.js 10 LTS:

Node.js 10.x is the latest LTS version of Node.js at the time of this writing. Luckily, it is available in the official package repository of Debian 10. So, you can easily install it using the APT package manager on your Debian 10 machine. First, update the APT package repository cache with the following command: $ sudo apt update The APT package repository cache should be updated. Now, install Node.js from the official Debian 10 package repository with the following command: $ sudo apt install nodejs Now, to confirm the installation, press Y and then press <Enter>. The APT package manager will download and install all the required packages. Node.js 10.x should be installed. As you can see, the Node.js version installed from the official package repository is v10.15.2. $ node --version Node.js has its own package repository to help you out in your work. Luckily, Debian 10 packages a lot of common and stable Node.js packages. You can easily download them from the official package repository of Debian 10. The Node.js Debian 10 package names start with node-* For example, I searched for express.js Node.js package on the official Debian 10 package repository. As you can see, the package exists. The express-generator package exists as well. The package names are node-express and node-express-generator in Debian 10. You can easily use the APT package manager to install these packages and use them in Node.js 10. I also searched for the Node.js package bluebird. It exists as well. If you rather want to install Node.js packages using NPM, then you have to install NPM from the official package repository of Debian 10 with the following command: $ sudo apt install npm Now, confirm the installation by press Y followed by <Enter>. The APT package manager will download and install all the required packages. At this point, NPM should be installed. As you can see, the NPM version installed from the Debian 10 package repository is 5.8.0. The Node.js packages that are in the Debian 10 package repository are very stable and well tested. You can use them if you want.

Installing Node.js 12:

At the time of this writing, the latest version of Node.js is version 12.x. But, it is not available in the official package repository of Debian 10. You have to install it manually from the official package repository of Node.js. Before you install Node.js 12.x, you have to install some dependency packages from the Debian 10 package repository. First, update the APT package repository cache with the following command: $ sudo apt update The APT package repository should be updated. Now, install the dependency packages build-essential and curl with the following command: $ sudo apt install build-essential curl Now, press Y and then press <Enter> to confirm the installation. The dependency packages should be installed. Now, add the official Node.js 12.x package repository with the following command: $ curl -sL https://deb.nodesource.com/setup_12.x</a> | sudo bash - The Node.js 12.x package repository should be added and the APT package repository cache should be updated. Now, install Node.js 12.x with the following command: $ sudo apt install nodejs The APT package manager should download and install all the required packages. Node.js 12.x should be installed. As you can see, I am running Node.js 12.7.0. $ node --version Node.js installed from the official Node.js package repository installs NPM by default. As you can see, I am running NPM 6.10.0.

Writing Your First Node.js Program:

In this section, I am going to show you how to write your first Node.js program. First, create a project directory (let’s call it ~/hello-node) as follows: $ mkdir ~/hello-node Now, navigate to the project directory ~/hello-node as follows: $ cd ~/hello-node Now, create a new file welcome.js in the project directory ~/hello-node and type in the following lines of code in the welcome.js file. let http = require('http'); const PORT = 8080; let server = http.createServer((req, res, next) => { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('<h1>Welcome to LinuxHint!</h1>');}); server.listen(PORT, () => { console.log("Visit http://localhost:" + PORT + " from your web browser.");}); The final welcome.js program looks as follows: Now, to run the Node.js program welcome.js, run the following command: $ node welcome.js As you can see, the welcome.js program is running. Now, visit http://localhost:8080 from your web browser and you should see a welcome message as shown in the screenshot below. So, that’s how you install Node.js on Debian 10 and run your first Node.js program. Thanks for reading this article.

Recognizing a face using JavaScript

What are the options? Many solutions exist for Machine Learning. When you look around for ways to identify faces, you come up with a host of solutions. Many are generic, some are interfaces to existing frameworks. For JavaScript, you have a few popular ones to choose from. You may even be confused by the array of solutions. Even for face recognition you have several options. Many, most actually, are for Python but you can also find a few. Frameworks that are aimed specifically at face recognition are face,js and face-recognition.js. The latter is considered obsolete though. The smallest, in terms of code, is pico.js With about 200 lines of code it can detect your own face using your webcam. The Pico code comes with a trained set already, which means that it will not improve while you are using it. For the curious, the pre-trained classification cascades are available on their GitHub repository. If you do want to train it yourself, there is a learn function you can use. This is a C program available on GitHub. This is a long process to complete making it an interesting exercise rather than something useful. One of the more interesting API’s is face-api.js, this one uses TensorFlow.js for the machine learning part.

How does it work?

The simplest example of machine Learning is a pair of parameters such as the petals of the iris flower. This is the most common initial data set when you want to start learning Machine Learning. The data can be summarised in simple tables.
Sepal length Sepal width Petal length Petal width Class
5.1 3.5 1.4 0.2 Iris Setosa
4.9 3.0 1.4 0.2 Iris Setosa
7.0 3.2 4.7 1.4 Iris Versicolor
6.4 3.2 4.5 1.5 Iris-versicolor
6.9 3.1 4.9 1.5 Iris-versicolor
6.3 3.3 6.0 2.5 Iris-virginica
5.8 2.7 5.1 1.9 Iris-virginica
As you can see from the table, it is now possible to find the sizes which best match a certain flower. This is not an absolute truth but it can get very accurate with enough data points. The question now becomes: How do you represent an image as a long list of values? Or a face for that matter? Well, the short story is that you convert the picture to the value of the intensity of each pixel. Starting from there, you can decide where lines and or points go that depict a face. What a face actually is has been determined by a pre-trained model. If you apply that to a number of pictures of the person you are trying to detect, then a table similar to the Iris one above can be used for determining which face it is. How it actually works is a bit more complex than that. For you to create your own solution, you need to use a library made for it. Fortunately, there are many free and open source solutions available.

What are the options?

There are many libraries for using JavaScript, one is face-api.js. The others may more capable choices but this one has a very simple demo page. You can download the demo page from GitHub. The page contains the library and the demo pages. If you want to start at a deeper level, you can check out TensorFlow and dlib. Face-api uses TensorFlow as a machine Learning library. Once you have everything downloaded from GitHub, you can use the examples library to explore different methods for face-recognition.

What are the use cases?

In industry, face recognition is used for access control, attendance checks and other security related case. In social media networks, your face can be tagged so that you can search for your face rather than your name. For your own system, you can use it for access to your computer and even control some of your applications.

 What are we developing?

We are making a simple system to detect a face.

To detect a face, you need to have the software, images and a trained model. You can train the model yourself and you should but for your specific task, you can also re-train an existing model. In this example, the model is pre-trained and downloaded. For the code to work, you need to collect the sample. In this case we use a webcam, simple enough with HTML5. To do this, add a video tag in the html code. <video id = "videoID" autoplay muted></video> Simple right? but wait you need to call this from your JavaScript also. const video = document.getElementById('videoID') Now you can use the constant to get your stream into the JavaScript code. Create a startVideo function. function startVideo() { navigator.mediaDevices.getUserMedia({ video: {} }, stream => video.srcObject = stream, err => console.error(err))} This is a general function that does not call the videoID, you need to set a function that calls the incoming stream. A way to catch the stream is to use Promise functions. Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri('/models'), faceapi.nets.faceLandmark68Net.loadFromUri('/models'), faceapi.nets.faceRecognitionNet.loadFromUri('/models'), faceapi.nets.faceExpressionNet.loadFromUri('/models')]).then(startVideo); The Promise statement above will now run the startVideo function when the stream is available. Finally, the video event listener below will run the functions available from the face API. video.addEventListener('play', () => {const canvas = faceapi.createCanvasFromMedia(video); document.body.append(canvas);const displaySize = { width: video.width, height: video.height }; faceapi.matchDimensions(canvas, displaySize); setInterval(async () => {const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();const resizedDetections = faceapi.resizeResults(detections, displaySize); canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); faceapi.draw.drawDetections(canvas, resizedDetections); faceapi.draw.drawFaceLandmarks(canvas, resizedDetections); faceapi.draw.drawFaceExpressions(canvas, resizedDetections);}, 100);});

What do you need in your development environment?

Since we are using JavaScript, we need nodejs, node and npm (or similar). your best tactic here is to create your development directory and then clone the repository from GitHub. The examples are in the examples directory so move there. $ cd examples/example-browser/ Inside the directory you need to install the packages using npm. $ npm install Since you are in the directory where you downloaded face-api.js, npm will find what you need to download. Next you can start the demo and open it in your browser. $ npm start The last line in the output shows the port you need to use in your browser. These examples are usually of the cast of Big Bang Theory but you can load in your own pictures and even use the webcam to determine your age. These demos are fun to play with but the real value is that the code is available to study. In the files, the JavaScript are separated in a separate directory to make it easy to use. For your pages to work you need to load in the API and all scripts you are going to use.

Conclusion

This is a very short example of how to use existing API’s to detect faces and recognise them. The really fascinating part is to find useful applications for the technology. What will you use it for? Access to your own machine or just some specific data or application?

Setting Up Node.js Development Environment

You can always install Node.js on your computer and run Node.js applications there. But, there are situations where you will want to use Docker to do your Node.js development. For example, let’s say, you don’t want to install Node.js on your computer and still want to develop Node.js applications or test an existing one. In that case, you can simply use a Node.js Docker container. Another example is where you need to test your Node.js application on different versions of Node.js. In that case, you can use different Node.js Docker containers with different version of Node.js installed to test your application. In this article, I will show you how to set up Node.js development environment using Docker. So, let’s get started.

 Setting Up Project Directory:

In this section, I will clone one of my Node.js API app from GitHub to my ~/Projects/ directory just for testing Docker Node.js development environment I am about to show you how to setup. This is not required. You can always use your own Node.js app if you want. First, I am going to navigate to my ~/Projects/ directory as follows: $ cd ~/Projects/ Now, I am going to clone my shovon8/angular-hero-api GitHub repository as follows: $ git clone https://github.com/shovon8/angular-hero-api The project files will be in the angular-hero-api/ directory as you can see in the screenshot below.

Node.js Docker Images:

There are official container images for different version of Node.js built on top of different Linux distribution on DockerHub. Visit https://hub.docker.com/_/node/ from your favorite browser to find the Node.js image you need. As you can see, the tag name for all the Node.js images are listed in the DockerHub page of Node.js. You can either use Debian Jessie/Stretch, Alpine, ChakraCore Linux distribution based images for different versions of Node.js. Usually, you don’t have to know much to use a Node.js Docker image. If you want to use Node.js version 12, then all you have to do is write node:12 when you make a container. For Node.js 10, it is node:10. For Node.js 8, it is node:8. It’s that simple.

Configuring the Node.js Development Environment:

In this section, I am going to configure Linux command aliases for my Node.js API app. That way, I can easily use any version of Node.js I want to run my app. In each of my Node.js project directory, I will create a new file source. In that file, I will keep the command aliases like node12 for Node.js 12 runtime, node10 for Node.js 10 runtime, node8 for Node.js 8 runtime running on Docker. You can reuse the same source file with slight modification on your other Node.js projects as well. First, navigate to your project directory as follows: $ cd angular-hero-api/ Now, create a source file with the following command: $ nano source Now, type in the following lines in the source file. alias node12='docker run -it --rm --name hero-api -p 4242:4242 -v "$PWD:/usr/src/app" -w /usr/src/app node:12'alias node10='docker run -it --rm --name hero-api -p 4242:4242 -v "$PWD:/usr/src/app" -w /usr/src/app node:10'alias node8='docker run -it --rm --name hero-api -p 4242:4242 -v "$PWD:/usr/src/app" -w /usr/src/app node:8' Here, -it means, run the container in interactive mode. –rm means remove the container automatically when it’s no longer needed. –name hero-api defines a name for the container. -p 4242:4242 means the container port 4242 is forwarded to the destination port (on your computer) 4242. The format of this option is -p destination:source. Remember, the first port before the colon (:) is the destination port. If you want to access your application on some other port than 4242 on your computer, then you have to change the destination port. If your applications run on some other port than 4242. Then you have to change the source port. NOTE: As I will only be using one of the containers at any one time, the name and destination port can be the same. If you wish to run or test your Node.js application on multiple Node.js version at the same time, then make sure the name and destination port is different for each of the containers in the source file. Once you’re done, save the file by pressing <Ctrl> + x followed by y and <Enter>. Now, enable the aliases with the following command: $ source source Now, you can run any version of node runtime whenever you need with node12, node10, node8 commands as you can see in the screenshot below.

Running Hero API Node.js App:

Now, let’s see how to run the angular-hero-api app from my GitHub repository with this setup. I am going to use Node.js 12 runtime first, then go for Node.js 10 and Node.js 8 runtime to show you that it works in each of the versions. The API app does not have any node modules installed. So, you have to install all the required node modules with npm install command as follows: $ node12 npm install The node modules are installed as you can see in the screenshot below. Now, run the Node.js API app as follows: $ node12 npm run test As you can see, the API server is running on port 4242 on the container. I also forwarded the port to 4242 on my computer. So, I should be able to access it on port 4242. Yes, I can access it. It’s working as expected. Now, stop the container by pressing <Ctrl> + c. Let’s try to run the API app with Node.js version 10. $ node10 npm run test As you can see, it’s running. It works for Node.js 10 as well. Finally, let’s try for Node.js version 8. $ node8 npm run test The API app is running on Node.js 8 runtime as well. Perfect! It works correctly. So, that’s how you set up Node.js development environment using Docker. Thanks for reading this article.

NodeJS with Redis

Redis is widely used as a caching server. At times, Redis is used as a database as well. It stores the data in a computer’s memory (RAM) directly. The advantage is that it can access the data very fast. The disadvantage is that the data it stores is temporary. If you reboot your computer, then all the data will be gone. In this article, I will show you how to use Redis with Node.js. I will be using Node.js 10.x on Debian 9 Stretch in this article. But any modern version of Node.js should work. So, let’s get started. To get started you must have the following requirements: js and NPM installed on your computer. Redis installed on your computer. You should be able to find articles on installing Node.js and NPM on your desired Linux distribution on LinuxHint.com. I’ve written a dedicated article on installing Redis on Ubuntu/Debian.

 Starting Redis:

You can check whether redis service is running with the following command: $ sudo systemctl status redis As you can see, redis service is running. If redis service is not running in your case, start it with the following command: $ sudo systemctl start redis

Initializing the Project Directory:

First, create a project directory (let’s call it node-redis) with the following command: $ mkdir ~/node-redis Now navigate to the project directory ~/node-redis $ cd ~/node-redis Now create a package.json file: $ npm init -y

Installing Redis Node.js Module:

There are many Redis clients for Node.js. The official website of Redis recommends redis. You can easily install the redis Node.js module using NPM (Node Package Manager). To install redis Node.js module, run the following NPM command: $ npm install redis --save redis Node.js module should be installed.

Connecting to Redis using Node.js:

In this section, I am going to show you how to connect to Redis data store using Node.js. First, create a new file connect.js in your project directory and type in the following commands in it: Here, line 1 imports the redis module. Line 2 creates a Redis client. As I am running Redis on the same computer as the Node.js programs are running, I didn’t have to specify the hostname or IP address and port where the Redis server is running. If you’re running Redis server on a different computer or server, then you will have to specify it here. For example, let’s say, your Redis server is running on port 6379 on a computer which has the IP address 192.168.10.87, then you would write line 2 as: let client = redis.createClient(6379, '192.168.10.87'); Line 4-6 is used to print a message to the console if we can connect to the Redis server. Line 9-10 is used to print a message to the console if we are unable to connect to the Redis server. Now, run the connect.js Node.js script as follows: $ node connect.js As you can see, I am connected to the Redis server.

Storing Data in Redis Using Node.js:

In this section, I will show you how to store data (key-value pairs) in Redis data store with Node.js First, create set1.js file in your project directory and type in the following lines in it: Here, line 1 and 2 are the same as in connect.js. On line 4, I set the callback function of the connect event to storeData. So, when our Redis client is connected to the Redis server, the function storeData is called. On line 6-10, the callback function storeData is defined. On line 7 and 8, I used set(key, value) method of RedisClient object to set the key name and country to value Mary Smith and USA respectively. Now, run set1.js as follows: $ node set1.js As you can see, the key-value pairs are set.

Retrieving Data from Redis Using Node.js

In this section, I will show you how to retrieve data from Redis data store using Node.js. First, create a new file get1.js in your project directory and type in the following lines: Here, on line 4, getData function is set as a callback function for the connect event of RedisClient. On line 6-9, the getData function is defined. On line 7, I called the get(key, callback) method of RedisClient object. name here is the key of the value you want to retrieve. get() method calls the printValue callback function before it finishes running. On line 11-18, the error first style callback function printValue() is defined. It accepts 2 arguments, error and result. If any error occurs, then it’s printed on the console and the function exits. If there’s no error, then the value for the certain key is printed on the console. On line 8, the same thing happens. Now, run get1.js as follows: $ node get1.js As you can see, the values for the keys name and country is retrieved from the Redis data store.

Storing Objects in Redis with Node.js:

You can store JavaScript objects in Redis data store. First, create a new file set2.js in your project directory and type in the following lines in it. Here, everything is the same as in set1.js file that I already explained earlier. The only difference is, I used client.hmset(key, object) method of RedisClient object in setData() callback function. In line 7-10, I used client.hmset() method to store a JavaScript object in the Redis data store against the key C011. Now run set2.js Node.js script as follows: $ node set2.js As you can see, the object is stored.

Retrieving Objects from Redis with Node.js:

In this section, I am going to show you how to retrieve objects from Redis data store. Fist, create a new file get2.js in your project directory and type in the following lines in it. Here, everything is the same as in get1.js script I explained earlier. You can retrieve a JavaScript object very easily with client.hgetall(key, callback) method of RedisClient as in line 7-9. Now run get2.js Node.js script as follows: $ node get2.js As you can see, the JavaScript object is retrieved from the Redis data store. I showed you how to setup Redis with Node.js in this article. Now you should be able to read the redis Node.js module documentation at http://redis.js.org and learn more about it. Thanks for reading this article.

Node.js Send E-Mail with Attachment

Node.js is the server side JavaScript engine that is loved by web developers and system administrators all over the world. Node.js has a rich set of modules that you can install using Node Package Manager (NPM) and use to do almost any task. There are many Node.js modules for sending E-Mails using Node.js such as Nodemailer, emailjs, express-mailer etc. In this article, I will show you how to send E-Mail and also how to send E-Mail with attachment with Nodemailer Node.js module. Let’s get started.

Requirements:

To follow this article, you should have: Basic understanding of Node.js and JavaScript. js 6.x or later installed on your computer. NPM installed on your computer. An E-Mail account such as GMail. A Text Editor for writing Node.js codes. You should be able to find dedicated articles on each of these topics on linuxhint.com. Be sure to check them for more information.

 Creating Project Directory:

It’s always best to create a new directory for every Node.js app you write. Because by default, Node.js modules are installed in node_modules/ directory inside your current working directory. That way, modules are separate for each app you write and you can use different version of the same module in different app. This is a lot flexible than installing modules globally. Create a project directory (let’s call it node-mail) with the following command: $ mkdir node-mail Now navigate to the project directory with the following command: $ cd node-mail Now create a package.json file with the following command: $ npm init -y As you can see, a basic package.json file is created.

Installing Nodemailer:

In this section, I am going to show you how to install Nodemailer Node.js module using NPM. First, make sure Node.js is installed and working correctly with the following command: $ node --version As you can see, Node.js 10.11.0 is installed and working correctly in my computer. The version on your computer may be different. It’s alright but it should be version 6.x or later. Otherwise Nodemailer won’t work. Now, make sure NPM is installed and working correctly with the following command: $ npm ---version As you can see, NPM 6.4.1 is installed and working correctly in my computer. The version on your computer may be different. It’s alright. You need internet connectivity in order to install Nodemailer using NPM. So make sure you’re connected to the internet. Now, install Nodemailer Node.js module using NPM with the following command: $ npm install nodemailer --save Nodemailer is installed.

Sending E-Mail with Nodemailer:

In this section, I will show you how to send E-Mail from your gmail account with Nodemailer. First, create a new file (let’s call it sendmail.js) in your project directory with the following command: $ touch sendmail.js Now type in the following lines of code in sendmail.js file and save it. Here, on line 1, I imported Nodemailer. On line 3, I set my email to myEmail variable. This is the email from which I will send an email to other email accounts. Make sure you change it to your email address. On line 5-11, a transport object is created. It is required to send an email using Nodemailer. The purpose of the transport object is to verify the sender information. You only need to do it once. Once the sender information is verified, a transport object should be created. On line 6, I set service to gmail as I am using a GMail account to send emails. The supported services are DynectEmail, Gmail, hot.ee, Hotmail, iCloud, mail.ee, Mail.Ru, Mailgun, Mailjet, Mandrill, Postmark, QQ, QQex, SendGrid, SES, Yahoo, yandex, Zoho. The service name is case insensitive. So you can put gmail or GMAIL or Gmail there. It’s all the same. Make sure you set the correct service name. NOTE: You can use your own email server as well. To do that, you have to create a custom Nodemailer Transport object. To learn more about it, visit the official documentation of Nodemailer at https://nodemailer.com/smtp/ On line 9, I put the password of my gmail account that I am using to send emails from. Make sure you change it to yours. On line 14-19, I created a message object. In this object, from is set to the email address of the sender, to is the email address of the receiver. subject is the subject of the email and text is the content of the email. On line 22, I used the transport.sendMail() method to send email using Nodemailer. The first argument of the sendMail() method is the message object defined on line 14-19. The second argument is a callback function. The callback function simply checks for errors and prints a message to the console depending on whether the email was sent or not. Now run the sendmail.js script as follows: $ node sendmail.js As you can see, the email was sent. I checked my Gmail, and voila! I received the email just fine.

Sending E-Mail with Attachment Using Nodemailer:

Now that you know how to send email using Nodemailer, sending email with attachment is a piece of cake! To send email with attachment, all you need to do is modify the message object on line 14-19 and the rest of the code should be the same. Change the message object as follows as save the file. Here, attachments is an array objects. Each object defines an attachment file. So you can send multiple files at once. On line 20-22, I set the relative path to a file hello.txt to the path property of the object. Now run the sendmail.js script again. $ node sendmail.js As you can see, the email was sent. As you can see, I received the message along with the attachment hello.txt. You can also set custom name to your attachment file. For that, you have to change the attachment object as follows: To send multiple attachments, create multiple attachment objects as follows: That’s how you send email with attachment using Nodemailer in Node.js. Thanks for reading this article.

NodeJS Debugger Tutorial

No matter how good you are at programming NodeJS, there will always be things happening that you don’t want. So debugging a NodeJS app is very important to find and fix the problems and get the app running as soon as possible. NodeJS has powerful debugging features build in, which is really helpful. You can use the NodeJS debugger from the command line very easily. In this article, I will show you how to use the NodeJS debugger. I am using NodeJS 8 on Debian 9 Stretch for the demonstration. But everything shown in this article should work on any latest NodeJS version on any Linux distributions, Mac OS and Windows. So Let’s get started.

Installing NodeJS:

NodeJS may not be installed on your computer by default. But it is freely available to download and install. Just go to the official website of NodeJS at https://nodejs.org/en/ and download NodeJS for your operating system. It is available for Mac OS, Linux and Windows. So no matter what operating system you have, you should be able to install it.

 Setting Up the Test Program:

The NodeJS program I used in this article is given below: This is a simple NodeJS program that adds 2 numbers. You can run the NodeJS script app.js with the following command: $ node app.js In the next section, I will show you how to use the NodeJS debugger.

 Starting NodeJS Debugger:

To debug the NodeJS script app.js, you have to run the script app.js with the NodeJS debugger. You can start the NodeJS debugger for app.js the following command: $ node inspect app.js NOTE: On older version of NodeJS, you run node debug app.js instead to start the NodeJS debugger. NodeJS debugger should start as you can see in the screenshot below. Now you can run many commands here to debug the NodeJS script app.js.

Getting Help with NodeJS Debugger:

You can run the following command to get a list of commands and functions that you can use to debug a NodeJS script in the NodeJS debugger: debug> help As you can see, all the commands and functions with short description of what they do are listed. When you are having a hard time remembering what commands or functions to run, this is a good place to get some help.

Auto Completion on NodeJS Debugger:

You can partially type in a command or function and press <Tab> to get auto completion. Before pressing <Tab>: After pressing <Tab>. As you can see, the function is auto completed. In the next sections, I will show you how to do different debugging task with NodeJS debugger.

Setting Breakpoints with NodeJS Debugger:

A NodeJS script has many numbered lines when viewed in a programming text editor. You can set breakpoints on any of these lines. Let’s say you set a breakpoint on line 3, and start the NodeJS script. Then the NodeJS debugger would run line 1 and 2 and stop at line 3. Then you can check whether the results up until this point is correct and continue the program as usual. You can set as many breakpoints as you need. To set a breakpoint, you run the setBreakpoint() function. The function accepts an integer parameter as line number to which you want to set a breakpoint. setBreakpoint(int lineNumber) To set a breakpoint on line 3, Run the following command: debug> setBreakpoint(3) As you can see, a breakpoint is set on line 3, which is marked by an arrow (>). Now let’s set a breakpoint on line 22 as well: debug> setBreakpoint(22) As you can see, a breakpoint is set on line 22 as well, just before the first addNumber() function is executed.

Removing or Clearing Breakpoints with NodeJS Debugger:

To remove a breakpoint, just run the clearBreakpoint() function. clearBreakpoint(int lineNumber) Pass in the line number at which you have a breakpoint set as an argument to the function clearBreakpoint(), the breakpoint should be removed or cleared.

Listing All the Breakpoints with NodeJS Debugger:

You can list all the breakpoints you have already set with the NodeJS debugger with the following command: debug> breakpoints As you can see, I have breakpoints set on line 3 and line 22.

Using REPL in NodeJS Debugger:

The full form of REPL is Read–Eval–Print Loop. You can use REPL in NodeJS debugger to check the contents of variables and functions and many more. It is really useful. To start REPL, run the following command: debug> repl As you can see, REPL has started. Now you can press <Tab> twice to see what variables and functions are available at the moment in your NodeJS script. You can also print the content of any variable you wish. Just type in the name of the variable and press <Enter>. You can also check functions as well. To exit REPL, press <Ctrl> + c. You should be back to the debugger.

Using the cont Command in NodeJS Debugger:

Now that you have all the breakpoints set, you can run the cont command or c command to continue running the lines till the first breakpoint. debug> c Now I can check the value of x and y from REPL and as you can see it is correct. To go to the next breakpoint, you can run c command again. The variables are printed with REPL. Running the c command again completes the program as there are no more breakpoints.

Resetting Program Execution:

If you want to start executing lines from the beginning of your NodeJS script, you have to reset the debugger. You can reset the debugger with the following command: $ r

Debugging NodeJS Script Line By Line:

You can use the next or n command to run a NodeJS script line by line. At first, I have no value set for x and y. I executed 1 line: debug> n Now x is set to 5 and y is still undefined. You can move line by line and keep debugging your NodeJS script like this. Though there are many things I could not cover, but this is the basics of using the NodeJS debugger to debug a NodeJS app. Now it should be easy to learn more about NodeJS debugger with the help command.

How to Install and Configure NodeJS on CentOS 7

JavaScript is the programming language of the Web. It is mainly used in Web browser to make your website interactive. But a web browser is not the only place JavaScript is used these days. JavaScript can be used just like any other interpreted programming languages such as Python, Ruby etc. NodeJS made it possible. NodeJS is basically JavaScript on the server.In this article, I will show you how to install and configure NodeJS on CentOS 7. Let’s get started.

Installing Build Tools for Native Addons:

All the NodeJS modules are written. At times that has performance issues as JavaScript is not as fast as a compiled language such as C and C++. To solve this problem, NodeJS has native addons. How that work is, NodeJS relies on Chrome V8 JavaScript engine, which is written in C++. So NodeJS adds an additional layer to compile JavaScript code to native binary code. This improves performance drastically. NodeJS codes runs almost as fast as C and C++ compiled code if the NodeJS module that you’re using is written using the Native Addons NodeJS API. The NodeJS native addons needs a C++ build tool installed on your computer as the modules are built while you install them using Node Package Manager. I will show you how to install build tools here. First update the YUM package repository cache with the following command: $ sudo yum makecache The YUM package repository cache should be updated. Now install build tools on your CentOS 7 machine with the following command: $ sudo yum install gcc-c++ make Now press y and then press <Enter>. The build tools should be installed.

Adding NodeJS Package Repository on CentOS 7:

At the time of this writing, you can install either NodeJS 8.x or NodeJS 10.x. NodeJS 8 is the LTS release and NodeJS 10 is latest release. Both of these versions are available to install on CentOS 7. Add the package repository of either NodeJS 8.x or NodeJS 10.x depending on your need. For NodeJS 8.x: Run the following command to add the package repository of NodeJS 8.x on your CentOS 7 machine: $ curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash - For NodeJS 10.x: Run the following command to add the package repository of NodeJS 10.x on your CentOS 7 machine: $ curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash - I went for the LTS release of NodeJS, which is version 8.x. As you can see, the package repository is added.

Installing NodeJS:

Now you can install NodeJS on your CentOS 7 machine with the following command: $ sudo yum install nodejs Now press y and then press <Enter> to continue. Now press y and then press <Enter> to accept the GPG key. NodeJS should be installed. Now run the following command to verify whether NodeJS is working: $ node --version As you can see, NodeJS is working properly. Now run the following command to see whether Node Package Manager (NPM) is working: $ npm --version As you can see, NPM is working correctly as well.

Using NodeJS:

Now that you have NodeJS installed, I am going to show you the basics of NodeJS. First create a project directory with the following command: $ mkdir hello-world Now navigate to the project directory: $ cd hello-world/ Inside hello-world/ directory, initialize a Node package.json file with the following command: $ npm init -y As you can see a package.json file is generated. The contents of the file are also printed on the terminal. It is a JSON file. Here, name is the application name, version is the application version, description is a short description about your application, main is the name of a NodeJS script in your project directory that is used to start your application. By default, it is index.js, but you can change it. scripts is an object that holds command aliases. I am going to leave the defaults for now. Now install Express.js NodeJS package with NPM with the following command: $ sudo npm install express --save Express should be installed. All the modules are kept in the node_modules/ directory in your project directory. Now create a index.js file and type in the following codes: let express = require('express'); let app = express(); app.get('/', (req, res) => { res.end('<h1>Welcome to LinuxHint</h1>');}); app.listen(8080, () => { console.log('App is running on http://localhost:8080');}); Now run the following command to start the app: $ node index.js The app should start. Now from your web browser, go to http://localhost:8080 and you should see the following output. The NodeJS app is working correctly. Now to stop the app, press <Ctrl> + c on the terminal. Now if you visit http://localhost:8080 from the web browser, you should see an error. That’s how you install and configure NodeJS on CentOS 7.

How to Install and Use NPM on Debian 9 Stretch

NPM or Node Package Manager is the same thing as APT to Debian. It is used to install, remove, update NodeJS packages. In this article, I will show you how to install and use NPM on Debian 9 Stretch.

 Installing NodeJS and NPM

The version of NodeJS available in the official Debian 9 Stretch package repository is 4.x, which is very old. The official package repository of Debian 9 Stretch does not have NPM. In this section, I will install the latest stable version of NodeJS and NPM which is at the time of this writing 8.11.1. First update the apt package repository cache with the following command: $ sudo apt-get update Now install CURL with the following command: $ sudo apt-get install curl Press y and then press <Enter> to continue. CURL should be installed. Now add the package repository of NodeJS 8.x with the following command: $ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - The NodeJS 8.x package repository should be added as you can see from the screenshot below. Now you can install NodeJS and NPM all together along with the development tools for building native NodeJS modules with the following command: $ sudo apt-get install build-essential nodejs Now press y and then press <Enter> to continue. NodeJS, NPM and the required build tools for compiling NodeJS native modules are installed. Now check whether NodeJS is working with the following command: $ node --version As you can see, NodeJS 8.11.1 is installed and working correctly. Now check whether NPM is working with the following command: $ npm --version As you can see NPM is installed correctly as well.

Using NPM

In this section, I will show you how to use NPM to manager NodeJS modules or packages. Before that, let’s talk about global packages and local packages. If you install a NodeJS package globally, then it should be saved somewhere /usr/lib/node_modules directory and you can access it from any NodeJS project. If you install a NodeJS package locally, then a directory node_modules/ should be created on your project directory and the package should be saved in node_modules/ directory relative to your project directory. It can only be accessed from that project. That’s all you need to know for now. Let’s continue.

Creating a package.json Configuration File with NPM:

Every NodeJS project has a package.json file in its project’s root directory. This file holds information about your project, such as the name of the project, the version of the project, the dependencies or other NodeJS packages your project depends on and many more. You can manually create a package.json file and put all these information or you can use NPM to create it for you. First create a new directory node-project (you can name is whatever you want) for your NodeJS project with the following command: $ mkdir node-project Now navigate to your project directory with the following command: $ cd node-project Now to create a package.json file with NPM, run the following command: $ npm init Fill in the details and press <Enter> to move forward. In the end, type in yes and press <Enter>. As you can see, a package.json file is created. This is the contents of the package.json file:

Installing a NodeJS Package Locally with NPM:

If you know the name of the package, then you can easily install it using NPM. For example, if you want to install express NodeJS package, which is Express web framework, run the following command from your project directory: $ npm install express --save express NodeJS package should be installed.

Installing a NodeJS Package Globally with NPM:

You can install a NodeJS package globally from any directory. For example, if you want to install express NodeJS package globally, run the following command: $ sudo npm -g install express It should be installed globally.

Removing a NodeJS Package Locally with NPM:

If you want to remove a NodeJS package, let’s say express, from your project directory, run the following command from your project directory: $ npm uninstall express --save The express NodeJS package is removed.

Removing a NodeJS Package Globally with NPM:

To remove a NodeJS package, let’s say express, globally, run the following command: $ sudo npm -g uninstall express It should be removed.

Searching for NodeJS Packages:

Well, now you know how to install and remove NodeJS packages with NPM. Now the question is, how do I know what I can install with NPM? What packages are available? Well, you can search for packages in the NPM’s official website at https://www.npmjs.com/ or you can use NPM command line utility. To search for NodeJS packages from your web browser, go to https://www.npmjs.com/ and search for what you’re looking for. Type in the keywords as marked in the screenshot below, and press <Enter>. You should see a lot of packages as you can see in the marked section of the screenshot below. You can click on any one of them to see more information about that package. You can also run the following command to search for NPM packages: $ npm search "Web framework" As you can see, the same list is displayed. You can pick up the package name from the first column as marked in the screenshot below, and install what you need using NPM. So that’s how you install and use NPM on Debian 9 Stretch. Thanks for reading this article.

Creating Charts using JavaScript and PHP

Web based chart can be created by using any client-side library or server-side library based on static or dynamic data. If you want to create animated charts and want to download the chart faster then it is better to use a client-side chart library. Many client-side libraries are available to create charts for web pages. One of the popular client-side libraries is CanvasJS which can be used to create web based charts by using fixed data or retrieving data from any database. CanvasJS is used with PHP in this tutorial for creating web based charts. This library supports various types of charts, such as bar chart, column chart, dynamic column chart, line chart, pie chart, pyramid chart, doughnut chart, bubble chart etc. Some of them are shown here by using sample data. Before starting this tutorial, you must ensure that your web server and PHP are installed properly and working.

 Download CanvasJS

It is available in free and commercial version. You can download and use the free version of this library for testing purposes. Go to the following URL and click on Download link to download CanvasJS library. Unzip the file and store the folder in web server after download to use it. https://canvasjs.com <?php $profitdata = array( array("x"=> 2013, "y"=> 440000), array("x"=> 2014, "y"=> 270000), array("x"=> 2015, "y"=> 210000, "indexLabel"=> "Lowest"), array("x"=> 2016, "y"=> 600000), array("x"=> 2017, "y"=> 630000, "indexLabel"=> "Highest"), array("x"=> 2018, "y"=> 560000) ); ?> <html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script> window.onload = function () { var chart = new CanvasJS.Chart("displaychart", {//Enable animation animationEnabled: true, //To save the chart as image exportEnabled: true, //The others values of theme are "light1", "light2", "dark1" theme: "dark2", title:{ text: "Yearly Profits"}, data: [{//Change type to bar, line, pie etc. to change the display type: "column", indexLabelFontColor: "#5A3457", indexLabelPlacement: "outside",//Read data from PHP array in JSON format dataPoints: <?php echo json_encode($profitdata, JSON_NUMERIC_CHECK); ?>}]}); chart.render(); }</script></head><body><center><h3>Column Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%; align:center;"></div></center></body></html> Output: The following output will be generated if you run the file from any web server. “Trial Version“ and “CanvasJS.com” watermarks will be shown for free version. When you click on “More Options” button from top right corner then three options will be shown. You can print the chart or save the chart as JPG or PNG image format. If you click on “Save as PNG” option then the following dialog box will appear. The default image file name is Chart.png. You can remove the watermarks from the image by using any photo editing software easily.

Pie Chart:

The following example shows the popularity of different Linux distributions using pie chart. Write the following code in a file named pie-chart.php and store the file in var/www/html/jschart folder. <?php $popularity = array( array("os"=> "Arch Linux", "y"=> 40), array("os"=> "CentOS", "y"=> 25), array("os"=> "Debian", "y"=> 12), array("os"=> "Fedora", "y"=> 10), array("os"=> "Gentoo", "y"=> 8), array("os"=> "Lindows", "y"=> 5)); ?> <html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script> window.onload = function () { var chart = new CanvasJS.Chart("displaychart", {//Enable animation animationEnabled: true,//To save the chart as image exportEnabled: true,//The others values of theme are "light1","dark1", "dark2" theme: "dark1", title:{ text: "Popularity of Linux Distributions"}, data: [{//Change type to bar, line, column etc. to change the display type: "pie",//Set font color for the label indexLabelFontColor: "yellow",//format the percentage values yValueFormatString: "##0.00'%'",//Set angle for pie startAngle: 240, indexLabel: "{os} {y}",//Read data from PHP array in JSON format dataPoints: <?php echo json_encode($popularity, JSON_NUMERIC_CHECK); ?>}]}); chart.render(); }</script></head><body><center><h3>Pie Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%;"></div></center></body></html> Output: The following output will display if you run the file from web server. You can create image file of the chart by the step which is shown in the previous example.

Dynamic Column Chart:

You can create nice looking dynamic chart by using this library. Suppose, you want to create live chart of stock market where stock price increases or decreases continuously. Write the following code in a file named dynamic-chart.php and store the file in var/www/html/jschart folder. <?php $stockdata = array( array("stock"=> "MSFT", "y"=> 92.67), array("stock"=> "LOW", "y"=> 88.89), array("stock"=> "INTC", "y"=> 52.15), array("stock"=> "ADI", "y"=> 91.78), array("stock"=> "ADBE", "y"=> 224.80), array("stock"=> "ABBV", "y"=> 94.30), array("stock"=> "AMD", "y"=> 10.27) ); ?> <html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script> window.onload = function () { var chart = new CanvasJS.Chart("displaychart", {//Enable animation animationEnabled: true,//To save the chart as image exportEnabled: true,//The others values of theme are "light1","dark1", "dark2" theme: "dark1", title:{ text: "Stock Market Values"}, data: [{//Change type to bar, line, column etc. to change the display type: "column",//Set font color for the label indexLabelFontColor: "red",//format the percentage values yValueFormatString: "##0.00'%'", indexLabel: "{y}",//Read data from PHP array in JSON format dataPoints: <?php echo json_encode($stockdata, JSON_NUMERIC_CHECK); ?>}]}); //Read stock names var stdata = chart.options.data[0].dataPoints; var st = new Array();for (var i = 0; i < stdata.length; i++) { st[i]= stdata[i].stock;} function updateChart() { var stockColor, deltaY, yVal, xVal; var dps = chart.options.data[0].dataPoints;for (var i = 0; i < dps.length; i++) { deltaY = Math.round(2 + Math.random() *(-2-2)); yVal = deltaY + dps[i].y > 0 ? dps[i].y + deltaY : 0; xVal = dps[i].stock; stockColor = yVal > 200 ? "#FF2500" : yVal >= 170 ? "#FF6000" : yVal < 170 ? "#6B8E23 ":null; dps[i] = {label: st[i], y: yVal, color: stockColor};} chart.options.data[0].dataPoints = dps; chart.render();}; updateChart(); setInterval(function() {updateChart()}, 500);}</script></head><body><center><h3>Dynamic Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%;"></div></center></body></html> Output: The following output will display if you run the file from web server. You can create image file of the chart by similar way which is shown in the first example. By following above steps, you can easily create necessary web based animated charts using this useful JavaScript library.

Creating Charts using JavaScript and PHP

Node Package Manager, or npm, gets installed along with Node.js and you can use it to import software packages built on top of Node.js. If you are not familiar with the idea of nodejs, it is based off of Google Chrome’s JavaScript engine and can be used for server side scripting using JavaScript. It brings JavaScript (which traditionally runs on the client e.g a web browser) at the same footing as any other server side language like .NET or php. Because the language is already very popular and easy to use. There are now a myriad of applications built on top of the Node.js to the point that it almost has its own ecosystem of applications and frameworks to build applications each bundled as its own package. The problem with that arises when developers start to improve upon their packages and releases new version. Like most package managers, npm installs the most recent (stable) release of a package. So if you install a particular version of Express for your web application and a few years later after a new version of Express, chances are somethings in your app might break in a direct or indirect way. To circumvent this issue, it is handy to use npm in a way that makes use of version numbers to keep track of packages.

 Installing Node.js and npm

If you don’t already have Node.js installed in your system it is a good idea to start with the official LTS release. The official repository of Ubuntu 16.04 is a bit behind from the latest stable release and we would thus add the Node.js official repo as a PPA. $curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - The above command fetches a shell script from deb.nodesource.com and runs it via bash. The script automatically adds the public keys of the repo and updates the source lists for apt package manager. After this installing Node.js and npm is as easy as running: $apt install nodejs Now before we get started with installing and updating various packages, let’s make sure that the version of npm and Node.js is what we desire them to be. $nodejs --version $npm --version The version of npm is not the latest stable release (although we made sure that Node.js is the LTS version) To update npm itself you can run the command: $sudo npm install npm@latest -g Where the -g flag makes sure that the package is installed globally, that is, for all the users. You can only do this if you are the root user or have root previleges of the system. After which you can see that the version number for npm has changed. If you would like to go back you can enter the previous version number in a similar fashion. For example: $sudo npm install npm@5.6.0 -g

Installing and updating local packages

npm offers 2 different methods for installing packages. First is locally to be used in, say, another software that you are trying to build and the second method for installing it is to do it across the system for all users. This is great if you are trying to install a system utility, say with a CLI interface, to be used as a basic command or a standalone software. The local packages are directory specific. For example, if you are building a Node.js app first make project folder or directory: $mkdir myapp$cd myapp Now, from inside the directory you can run an npm init command and enter appropriate values for the name, description, git repository and other relevant fields which are the metadata of the package. Now if you install a package, such as lodash by running the following command in the directory: $npm install lodash npm automatically gets the latest stable release of the said package and installs it for you. If you want to check the version number then, enter the command: $npm list If a new version of lodash comes along and you wish to upgrade then, in the same directory, run: $npm update Now you can see that the version number is greater than what it was before. If something is wrong with the new version and you are facing issues, then you can always go back to previous state by simply running. $npm install lodash@4.17.0 Of course, that would require keeping track of the previous version number. Performing a git commit before any of the npm update actions is advisable for this reason.

Installing and updating global packages

Installing packages globally is actually much simpler since these are usually standalone utility. A great example of such a package is gtop which is similar to the top utility in Linux. It shows all the resource utilization in a clean and elegant way. To install a package globally, either be the root user or prefix your command with sudo if you are a user with root previleges. $sudo npm install gtop -g Now, like any command utility, you can call upon gtop by running: $gtop To exit simple hit q and you will fall back to the terminal. Because there are too many dependencies for gtop simply running npm list -g won’t help us know the verison of gtop. So we can try this instead: $npm list gtop -g If you want to update the package,then simply run: $sudo npm update gtop -g And you are done!

Conclusion

So that’s basic package management if you want to use npm packages for your new software project or as a standalone system utility. If you wish to explore npm packages you can always do so by going to their official website.

Using PostgreSQL from Node.js

PostgreSQL is a very popular open source database. It is widely used for almost all types of applications. Node.js has very good modules to work with PostgreSQL database. In this article, I am going to show you how to connect to a PostgreSQL database from Node.js. I will use a Node.js module called ‘node-postgres’ to integrate Node.js and PostgreSQL. Let’s get started.

 Pre-requisites:

First you have to make sure that Node.js, NPM and PostgreSQL are installed and running. You can install and configure PostgreSQL from How to Install PostgreSQL on Ubuntu Linux: The Easy Way and Node.js and NPM from How to install NPM if you don’t have them installed already. Now check whether Node.js is working with the following command: $ node --version Now check whether NPM is working with the following command: $ npm --version Now check whether PostgreSQL is working with the following command: Now create a directory ‘postgre-node’. Then navigate to the directory you just created with the following command: $ cd Documents/postgre-node Then you should run the following command to create a ‘package.json’ file. $ npm init -y You can see from the screenshot below that a ‘package.json’ file is created. Now install ‘node-postgres’ Node.js module using NPM with the following command. If you remember, ‘node-postgres’ is a PostgreSQL Client for Node.js. $ npm install --save pg ‘node-postgres’ should be installed.

Using ‘node-postgres’ PostgreSQL Node.js Client:

Now inside the directory ‘postgres-node’, create a new file ‘index.js’ and write the following codes as shown in the screenshot below. const pg = require(‘pg’); const pool = new pg.Pool({ user: ‘sysadmin’, host: ‘127.0.0.1’, database: ‘mywebstore’, password: ‘123’, port: ‘5432’}); pool.query(“SELECT NOW()”, (err, res) => { console.log(err, res); pool.end(); }); Here const pg = require(‘pg’) imports ‘node-postgres’ Node.js module. Then I created a Pool using pg.Pool with PostgreSQL login credentials. I didn’t change anything from the article for setting up PostgreSQL in the “Pre-requisites” section. You may take a look at it again. I simply retrieved the current date and time using the PostgreSQL NOW() function using pool.query()method of ‘node-postgres’. I ran SQL statements “SELECT NOW()”. Now if I save the ‘index.js’ file and run the Node.js source file with the following command: $ node index.js You should see current TIMESTAMP on the output as shown in the screenshot below.

Creating a Table:

Now I am going to create a new Table ‘users’ using the following query: # CREATE TABLE users(id SERIAL PRIMARY KEY, firstName VARCHAR(40) NOT NULL, lastName VARCHAR(40) NOT NULL) The ‘users’ table has 3 fields, id, firstName and lastName. id is an integer and firstName and lastName fields are strings. The source code is given on the screenshot given below. const pg = require(‘pg’); const pool = new pg.Pool({ user: ‘sysadmin’, host: ‘127.0.0.1’, database: ‘mywebstore’, password: ‘123’, port: ‘5432’}); pool.query(“CREATE TABLE users(id SERIAL PRIMARY KEY, firstname VARCHAR(40) NOT NULL, lastName VARCHAR(40) NOT NULL)”, (err, res) => { console.log(err, res); pool.end(); }); Now if I run the code, you should see the following output. Now let’s login to the ‘mywebstore’ datastore as ‘sysadmin’ user with the following command: $ psql -U sysadmin -h127.0.0.1 mywebstore It should ask you for the ‘mywebstore’ datastore’s password. Type in the password and press <Enter> You should be logged into the PostgreSQL console as shown in the screen below. Now run the following command to see all the tables: mywebstore=> \dt You should see ‘users’ table as shown in the screenshot. You can run the following command to quit PostgreSQL command line interface: mywebstore=> \q

Inserting into Table:

Now you can insert into the ‘users’ table with the following command: # INSERT INTO users(id, firstName, lastName) VALUES(1, ‘Shahriar’, ‘Shovon’) The source code is given in the screenshot below. Now if you run the source code, you should see the following output. Now you can login to the PostgreSQL command line interface with the following command like before: $ psql -U sysadmin -h127.0.0.1 mywebstore Run the following SQL query: $ SELECT * FROM users; You should see the data you inserted as shown in the screenshot below.

Retrieving Data from PostgreSQL:

You simply execute the following SQL statement to retrieve the data: # SELECT * FROM users; The other steps are similar. So I am not going to explain them again as it is out of scope of this article.

Updating data:

To update an existing row of PostgreSQL’s users table, run the following SQL query: # UPDATE users SET firstName=’Shovon’, lastName=’Shahriar’ WHERE id=1 Here ‘id’ is the primary key which is unique to each column of the users table. After you run this code, firstName and lastName should be updated as shown in the screenshot below.

Deleting a Column from PostgreSQL:

You can run the following SQL statement to delete a column from the PostgreSQL. # DELETE FROM users WHERE id=1 Here id is the primary key of the users table. Once you login to the PostgreSQL command line interface, you should not find the row you just deleted. In this case, I have an empty table. Because I had only 1 row in the users table. That’s how you perform CRUD operation with PostgreSQL using Node.js, and thanks for reading this article.

Get started with NodeJS on Ubuntu

NodeJS is an open-source server side framework built on JavaScript under MIT (Massachusetts Institute of Technology) license. It is mainly used for asynchronous programming and it is a very light weight framework that makes it faster than other frameworks. It is also supported by most of the popular operating systems. Different types of applications like web application, command line application, RESTful API etc. can be developed with this framework. How you can easily install and use this framework on Ubuntu are shown in this article.

 NodeJS Installation Steps

1.Press Ctrl+Alt+T to open the terminal and run the following command to install NodeJS $ sudo apt-get install -y nodejs After completing the installation process, type the following command to check the version of the installed framework. $ nodejs -v 2.To install necessary modules and packages you will need to install NodeJS package manager called npm. Run the following commands to install the npm. $ sudo npm install npm –global Check the version of npm. $ npm -v Now, NodeJS is ready to use for developing any application. How you can apply NodeJS as a beginner is shown in the next part of this article.

Using NodeJS

You can use NodeJS for various types of application development. As a beginner, how you can create a simple console application and a web server are shown in this part. Creating Console application Run the following commands to create a directory named nodejsapp for keeping your code organized, go to the newly created directory and open the nano editor for creating a JavaScript file named firstapp.js. $ mkdir nodejsapp $ cd nodejsapp $ nano firstapp.js Write the following code in the file to print a output in the console. Press Ctrl+x and then y to save the file and exit from the editor. console.log('First NodeJS Application'); Run the following command to execute the code of the firstapp.js file. $ nodejs firstapp.js if you get any permission problem to execute the script then you have to run the following command for setting execution permission of firstapp.js file and again run the above command. $ chmod +x firstapp.js

Creating Local Web Server

JavaScript is a popular client side scripting language which doesn’t require any web server to run. Web server is required to run any server side scripting language like php, asp etc. and you need to install a particular web server to run server side scripts. Using NodeJS framework, you can easily implement a local web server which can be used to run server side script. Open nano editor to create a new JavaScript file named server.js that will be used to create a local web server. $ nano server.js Add the following code in the file to create the server connection on port number 6060. According to this code, NodeJS will listen for server connection at localhost:6060 and if the connection can be established successfully then 200 code will be generated and ‘NodeJS App’ will be shown as output. var http = require('http'); var server = http.createServer(function(request response) { resquest.writeHead(200,{'Content-Type': 'text/plain'}); response.end('NodeJS App');}); server.listen(6060); console.log('Server is running at http://localhost:6060/'); Save the file by pressing Ctrl+x and y. Now, execute the following command to run the web server. If the code executes properly then the message ‘Server is running at http://localhost:6060’ will be displayed in the console. $ nodejs server.js Open any browser to check the web server code is working properly or not. The script will return ‘NodeJS App’as content in the browser if the above code executes properly. Type the following URL in the address bar for checking. http://localhost:6060 In the above example, a simple static text is displayed in the browser which is added as the content with response. But generally, any index file displays when the base URL executes. So, how you can attach any html file in the server connection script is shown in the next part. At first, create a very simple html file named index.html using Text Editor with the following code and save it in the nodejsapp directory which is created previously. <html><body> <center> <h2>Testing NodeJS Application </h2> <p> This is my first web application using NodeJS </p> </center></body></html> Now, create another JavaScript file named server2.js with the following code to view index.html file, after creating web server connection. Here, fs module is used to read the index.html file. Three types of outputs can be generated based on the code. If the connection establishes properly and index.html file exists then it will load the content of index.html file in the browser. If the connection establishes but index.html file does not exist on the current location then ‘Page is not found’ message will print. If the connection establishes and index.html file also exists but requested url is not correct then ‘Default content’ text will display as by default content. Port number 5000 is set as listening port here. So when web server connection establishes successfully then the message ‘Server is listening on 5000’ will show in the console. var http = require('http'); var fs = require('fs'); var server = http.createServer(function (request, response) { if (request.url === "/") { fs.readFile("index.html", function (error, pgResp) { if (error) { response.writeHead(404); response.write('Page is not found'); } else { response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(pgResp); } response.end(); }); } else { response.writeHead(200, { 'Content-Type': 'text/html' }); response.write('<h1>Default Content</h1>'); response.end(); }}); server.listen(5000); console.log('Server is listening on 5000'); Save the file and exit from the editor. Run the server by executing the following command. $ nodejs server2.js Type the following URL to view the content of index.html file in the browser. http://localhost:5000 Now, insert an invalid URL in the browser and check the output. http://localhost:5000/test Now modify server2.js file and set the file name as index2.html that does not exit and restart the server. Type the base URL again to check the output. NodeJS is a demanding framework and you can perform many tasks using it.